Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: anonymous filehandes?

by ides (Deacon)
on Jul 09, 2007 at 16:01 UTC ( #625640=note: print w/replies, xml ) Need Help??

in reply to anonymous filehandes?

Well the first is readable and the second one is too much magic for my tastes. The second requires a level of Perl knowledge you can't always assume in your fellow programmer.

Also, the first option gives you the chance to test your call to open for any failures ( permissions, file doesn't exist, etc ) and handle them.

In short the first version is more correct, the second should be relegated to perl one liners...

Frank Wiles <>

Replies are listed 'Best First'.
Re^2: anonymous filehandes?
by Anonymous Monk on Jul 09, 2007 at 16:10 UTC
    In the first example, files are opened & closed as iteration progresses. Is it correct to assume that in the second case files are collectively closed at the end of the script? Is the Perl interpreter smart enough to close files in the same manner as the first example?
      Is the Perl interpreter smart enough to close files in the same manner as the first example

      I'm 99.9999% sure that that is the case, without looking at the source. You can use the magic $ARGV variable to see where you are:

      my $prev; while (<>) { if (not defined $prev or $prev ne $ARGV) { print "now reading from $ARGV\n"; } print; $prev = $ARGV; }

      When run as "reader f1.txt f2.txt f3.txt" you'll be able to see when the program begins to read from the next file in the list. If you pipe into STDIN, it'll say "reading from -". I believe the most unambiguous terminology is to say that you are reading from the diamond operator.

      This is not obscure... it's useful.

      update: Oh, and, if you need to know when you reach the end of a file (not just when the new one begins), you can do that too, with eof.

      while (<>) { if (not defined $prev or $prev ne $ARGV) { print "reading $ARGV\n"; } print; print "and that's the end of $ARGV\n" if (eof); $prev = $ARGV; }

      When I get to that level of convoluted logic, however (especially if lots of other stuff is going on), my head usually explodes.

      • another intruder with the mooring in the heart of the Perl

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://625640]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2018-04-22 22:56 GMT
Find Nodes?
    Voting Booth?