Why does glob() work in while loop?

J

J. Romano

Dear Perl community,

I was recently explaining to a friend new to Perl about while loop
conditions and how they implictly assign a value to $_ only if the
condition looks like:

while (<HANDLE>)

and not like:

while (function())

To demonstrate an incorrect example, I executed this following code
that contains glob() in the while condition:


#!/usr/bin/perl
use strict;
use warnings;

while (glob("*"))
{
print "$_\n";
}
__END__


I was surprised to see that the program worked as expected! (That
is, it listed every file in my directory.) I didn't expect it to do
that, because I didn't think that the while condition would populate
$_ for me.

I played around a little more, and came up with a new script:


#!/usr/bin/perl
use strict;
use warnings;

{
my $num = 0;

sub getNextNum
{
return ++$num;
}
}

while (getNextNum())
{
print "$_\n";
sleep(1);
}
__END__


Instead of calling the glob() function in the while condition, the
getNextNum() function is called, which just returns an integer (the
first time it is called, it returns 1; every other time, it returns a
number one greater than the previous call).

Now, when I run this program, those new to Perl might expect that
the return value gets put in $_ and then gets printed out. Instead, I
get:

Use of uninitialized value in concatenation (.) or string at ... line
16.

which makes sense to me, because I know that the return value of
getNextNum() is never placed in $_.

But if the return value of getNextNum() is not placed in $_, then
doesn't that mean that the return value of glob() also should not be
placed in $_? If my reasoning is correct, why does the first program
I gave populate $_?

Thanks in advance for any explanations.

-- Jean-Luc
 
J

Jay Tilton

(e-mail address removed) (J. Romano) wrote:

: #!/usr/bin/perl
: use strict;
: use warnings;
:
: while (glob("*"))
: {
: print "$_\n";
: }
: __END__
:
:
: I was surprised to see that the program worked as expected! (That
: is, it listed every file in my directory.) I didn't expect it to do
: that, because I didn't think that the while condition would populate
: $_ for me.

[snip]

: But if the return value of getNextNum() is not placed in $_, then
: doesn't that mean that the return value of glob() also should not be
: placed in $_? If my reasoning is correct, why does the first program
: I gave populate $_?

This is explained in the documentation for the glob function. It's got a
splash of DWIM built in.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top