in reply to How to reset a variable for each file inside a while( <> ) loop?

Straight out of the docs for eof (thanks to the prompt from rminner++):
while (<>) { print "$.\n"; } continue { close ARGV if eof; # Not eof()! }
  • Comment on Re: How to reset a variable for each file inside a while( <> ) loop?
  • Download Code

Replies are listed 'Best First'.
Re^2: How to reset a variable for each file inside a while( <> ) loop?
by pat_mc (Pilgrim) on Jun 13, 2008 at 15:52 UTC
    Thanks, toolic - this looks interesting indeed.

    Since I am not familiar with the continue structure, can you please explain what exactly it is doing in your code?

    Thanks again!

    Pat
      I'm glad you asked because, as it turns out, continue is not even needed in this case. Here is the simplified code:
      while (<>) { print "$.\n"; close ARGV if eof; }
      I never use continue either; I just copied the code snippet (and tested it!) from the eof documentation. But, that code also used a next statement, which I deleted since it was not needed for your purposes. I should have also deleted the continue statement. I Read The Free Manual, as I'm sure you also did, which explains the relationship between continue and next.
      The continue allows you to call next in the loop without skipping "close ARGV if eof;".
        Thanks to all who took the time to reply and contribute to the discussion from which I learnt a lot!

        Based on the comments made I'd like to summarise the - in my view most elegant - solution to my question here: eof permits to detect the end of file, $ARGV holds the name of the file currently read and $. holds the current line number in that file.
        I just tested the following code snippet and it does exactly what I was looking for:
        while ( <> ) { print "Reading line $. in file $ARGV.\n"; $. = 0 if eof; }

        So, thanks again to all of you who contributed!

        Cheers -

        Pat
      The continue allows you to call next in the loop without skipping "close ARGV if eof;".