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

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

Thread Previous | Thread Next
From:
Paul Lalli
Date:
May 29, 2007 09:23
Subject:
Re: if (<FH>) VS while (<FH>)
Message ID:
1180451712.063366.153660@q75g2000hsh.googlegroups.com
On May 29, 9:29 am, jeevan.ing...@gmail.com (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
     write.)


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


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About