lezek has asked for the wisdom of the Perl Monks concerning the following question:

Out of interest today i tried the following code to see what would happen:

open (my $f, '<', 'input.txt'); while (<$f>) { print; } close $f;

To my enormous surprise, it worked perfectly. I tried it again with two files open at a time, and it still worked. It seems that whatever you pass as a filehandle comes back with a different value for each file, and what's more that value is actually valid.

I've never seen this in any documentation anywhere, and indeed either the camel or llama book (can't remember which) talks about using seperate modules to simulate scoped filehandles, which the above would seem to suggest is unnecessary.

So, is there some reason doing what I just did is a bad idea?

Replies are listed 'Best First'.
Re: open (my $f, ....)
by philcrow (Priest) on Feb 16, 2006 at 17:09 UTC
    So, is there some reason doing what I just did is a bad idea?

    On the contrary, Damian Conway's Perl Best Practices recommends this approach. But you should check the return value of open.

    Phil

      Thanks, I didn't know about it for some reason :). I will of course check the return value of open for important code ;).
Re: open (my $f, ....)
by dorward (Curate) on Feb 16, 2006 at 17:10 UTC

    From perldoc -f open:

    If FILEHANDLE is an undefined scalar variable (or array or hash element) the variable is assigned a reference to a new anonymous filehandle…

      Guh, I was reading the wrong page. I keep trying to use perldoc like man, for some reason. Thanks for the pointer.
Re: open (my $f, ....)
by brian_d_foy (Abbot) on Feb 16, 2006 at 18:55 UTC

    The latest edition of Learning Perl has an entire chapter on filehandle references, which also covers the three argument open. It was one of the larger issues prompting an update. ;)

    I also cover this in my TPJ article Getting More Out of Open.

    The various perldoc sections that talk about open probably need an update to emphasize the indirect filehandle now that it's much more popular. :)

    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review