On Fri, Feb 20, 2009 at 23:22, Chas. Owens <[email protected]> wrote:
> On Fri, Feb 20, 2009 at 22:56, itshardtogetone
> <[email protected]> wrote:
>> Hi,
>> Looking at the script below, why does the while function loop 6 times 
>> instead of 3 times when @data have only 3 elements and
>> I thought the output should be:-
>> 1 $_ = aaa    1
>> 2 $_ = bbb    2
>> 3 $_ = ccc    3
>>
>> Thanks
>>
>> #############################
>>
>> #!/usr/bin/perl
>> use strict;
>> use warnings;
>>
>> my @data = ('aaa 1','bbb 2','ccc 3');
>> my $ctr = 0;
>>
>> print "There are ",scalar @data," elements in \...@data\n";
>>
>> while (<@data>){
>>  $ctr ++;
>>  print "$ctr \$_ = $_\n";
>> }
>
> Wow, that is really odd.  I read that as the same as
>
> while (glob(@data)) {
>
> but that is obviously not what it is doing.  The construct you are
> looking for is the for loop:
>
> for my $element (@data) {
>    $ctr++;
>    print "$ctr \$element is $element\n";
> }
>
> I will try to figure out what is going on in your code,
snip

Well, it is in fact globbing.  I have never used a glob in scalar
context (which is what while puts things in), but from the docs:

    In scalar context, glob iterates through such filename
    expansions, returning undef when the list is exhausted.

and

    Since v5.6.0, Perl's CORE::glob() is implemented in terms of
    bsd_glob().  Note that they don't share the same
    prototype‐‐CORE::glob() only accepts a single argument.  Due to
    historical reasons, CORE::glob() will also split its argument on
    whitespace, treating it as multiple patterns, whereas bsd_glob()
    considers them as one pattern.

You can read more in the perldocs:
    http://perldoc.perl.org/functions/glob.html
    http://perldoc.perl.org/File/Glob.html

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/


Reply via email to