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

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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";
Damian

In reply to Re: Indirect Filehandles + use strict = error by TheDamian
in thread Indirect Filehandles + use strict = error by bowei_99

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-03-28 08:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found