develooper Front page | perl.beginners | Postings from May 2007

Re: if (<FH>) VS while (<FH>)

Thread Previous | Thread Next
Paul Lalli
May 29, 2007 09:23
Re: if (<FH>) VS while (<FH>)
Message ID:
On May 29, 9:29 am, (Jeevs) wrote:
> If (<FH>) ::: if doesn't not fill the $_ variable with contents of
> files first line automatically.
> While (<FH>) ::: while do fill the $_ to content of the files first
> line automatically.
> i.e
> open FH, "name.txt" or die "cant open";
> if  (<FH>){
> print "$_";
> }
> prints nothing
> If we change if to while $_ is set to first line of the file... how
> can this happen

Because it's a special case, very specifically designed to funtion the
way you just described.  From `perldoc perlop`:

     I/O Operators

     In scalar context, evaluating a filehandle in angle brackets
     yields the next line from that file (the newline, if any,
     included), or "undef" at end-of-file or on error.

     Ordinarily you must assign the returned value to a variable,
     but there is one situation where an automatic assignment
     happens.  If and only if the input symbol is the only thing
     inside the conditional of a "while" statement (even if
     disguised as a "for(;;)" loop), the value is automatically
     assigned to the global variable $_, destroying whatever was
     there previously.  (This may seem like an odd thing to you,
     but you'll use the construct in almost every Perl script you

Basically, Perl chose convenience rather than intuitiveness in this
case.  The creators decided that
while (defined ($_ = <FILE>) ) { ... }
would be written so often that they created a special case to let the
above be represented by simply:
while (<FILE>) { ... }

Hope this helps,
Paul Lalli

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About