Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

readdir and while - magic?

by bjelli (Pilgrim)
on Jan 03, 2003 at 15:16 UTC ( #224035=perlquestion: print w/ replies, xml ) Need Help??
bjelli has asked for the wisdom of the Perl Monks concerning the following question:

dear fellow monks,

why does ...

opendir(D, "test"); while ( $file = readdir(D) ) { print "$file is "; print ($file ? "true" : "false"); print "\n"; }

... work correctly, even for a filename like "0" that evaluates to false in boolean context? (see here for full code + output)

This seems to be an extreme case of "do-what-i-mean". I find it a little scary, because I don't know how it does what I mean ;-)

p.s.
I hit on this while doing research for my talk on php an perl at this years german perl workshop. the php counterpart looks appalingly complicated:

# this is php, not perl! $d = opendir('test); while (false !== ($file = readdir($d))) { print "$file is "; print ($file ? "true" : "false"); print "\n"; }

see also the php documentation.

--
Brigitte    'I never met a chocolate I didnt like'    Jellinek
http://www.horus.com/~bjelli/         http://perlwelt.horus.at

Comment on readdir and while - magic?
Select or Download Code
Re: readdir and while - magic?
by broquaint (Abbot) on Jan 03, 2003 at 15:22 UTC
    why does ... work correctly, even for a filename like "0" that evaluates to false in boolean context?
    Because it really looks like this under the hood
    opendir(D, "test"); while ( defined( $file = readdir(D) ) ) ...
    This is a DWIM perlism, nifty huh? I think it applies to any assignment in a while statement where the result of the assignment is evaluated for the condition, or something along those lines.
    HTH

    _________
    broquaint

Re: readdir and while - magic?
by jmcnamara (Monsignor) on Jan 03, 2003 at 15:28 UTC

    perl adds a defined to the while so you get something like this:
    $ perl -MO=Deparse -e 'while($file = readdir(D)) { print $file; }' while (defined($file = readdir D)) { print $file; } -e syntax OK

    This is explained in more detail at A most obscure bug.

    --
    John.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://224035]
Approved by gjb
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2015-07-01 23:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (24 votes), past polls