Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Indirect Filehandles + use strict = error

by TheDamian (Priest)
on Mar 14, 2006 at 10:20 UTC ( #536507=note: print w/replies, xml ) Need Help??

in reply to Indirect Filehandles + use strict = error

Hi all, I'm to use indirect filehandles, per Damian Conway's PBP, like so:
my $FH = "DATA"; open $FH, "<", $filename or croak "Cannot open file $ +filename $!\n";
Well, that's not quite how I said to do it in PBP. You missed one important caveat. From the book:
Whenever you call open with an undefined scalar variable as its first argument, open creates an anonymous filehandle (i.e. one that isnít stored in any symbol table), opens it, and puts a reference to it in the scalar variable you passed.

So you can open a file and store the resulting filehandle in a lexical variable, all in one statement, like so:

open my $FILE, '<', $filename or croak "Can't open '$filename': $OS_ERROR";

The my $FILE embedded in the open statement first declares a new lexical variable in the current scope. That variable is created in an undefined state, so the open fills it with a reference to the filehandle itís just created, as described above.

The key point being:
Whenever you call open with an undefined scalar variable as its first argument...
So you were nearly right. You just needed a little bit less code:
my $FH; open $FH, "<", $filename or croak "Cannot open file $filename $!\n";

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://536507]
zentara is thinking of moving to Mars to esacpe it all
[LanX]: Zentara eq Dr Manhatten ?
[zentara]: more like Dr. Helion3 :-)
[LanX]: Eily: though I haven't found a a reference for this one yet : Re^2: OT: Got fired this week (orange)

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (12)
As of 2017-03-27 15:26 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (320 votes). Check out past polls.