Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^5: File Reading and Closing confusion

by shmem (Chancellor)
on Aug 09, 2010 at 09:30 UTC ( [id://853757]=note: print w/replies, xml ) Need Help??


in reply to Re^4: File Reading and Closing confusion
in thread File Reading and Closing confusion

I was referring to being wary when $line=<FH> is used on its own.

Yes, but while takes care of that - and we/you were talking about a while loop, weren't you?

1.    while (<>) {
...
which is Perl short-hand for the more explicitly written version:
1.    LINE: while (defined($line = <ARGV>)) {
...

But of course,

We see that there is a possibility that a line read ($line3 in this case) may return undef.

- if you read past EOF, for instance. Then readline returns undef:

open(FH, "<", "a.txt") or die $!; my $line1 = <FH>; my $line2 = <FH>; print "eof!\n" if eof FH; my $line3 = <FH>; close FH; __END__ eof!
That's what I meant: we need to be wary that a line read will not always return defined.

That's exactly the condition when both the while($line = <FH>) { } and while(defined($line = <FH>)) { } loops terminate, so there's no difference in a while loop.

Replies are listed 'Best First'.
Re^6: File Reading and Closing confusion
by repellent (Priest) on Aug 09, 2010 at 15:37 UTC
      Yes, but while takes care of that - and we/you were talking about a while loop, weren't you?

    Yes and no. I was talking about:
    while (<FH>) { ... }

    VS
    $line = <FH>; # on its own / not as while condition

    Given the OP's prelude, I really thought that the OP was referring to these two cases. Sorry for the confusion! :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://853757]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2024-03-29 10:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found