Hi,

Gergely Buday <[EMAIL PROTECTED]> wrote:
> this is a working code snippet:
> 
> opendir (DIR, $dir) || die "Open failed: $!\n";
> 
> $\ = "\n";
> while ($_ = readdir(DIR)) { print; };
> 
> But when I try to use
> 
> while (readdir(DIR)) ...
> 
> my script writes only empty lines. It seems that the proper 
> number of empty lines are written. Does the prepended $_ 
> change readdir's calling context? Or any other explanation?

I'm assuming that you saw code like

        while( <FILEHANDLE> ) { print }

and thought that this would work similarly for functions in
gerebal.

That is, however, not true. The example given only works
because Perl does some trickery behind the scenes. The
giveaway is this snippet from the perlvar manpage:

    while (<>) {...}    # equivalent only in while!
    while (defined($_ = <>)) {...}

So what happens is that while( readdir(DIR) ) reads in the
directory, and then loops once for every entry in it.
However, it does not set or modify $_, which you can
verify by setting $_ to some value before the loop.

The behaviour you wanted is supplied by foreach().

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to