in reply to Re: Problem with Pack
in thread Problem with Pack

In Corion's most excellent answer, there is an extra line of code, with an incorrect comment.

The local *FILE isn't actually required. The following snippet works with no errors. Perl has special handling for all uppercase names, which it perceives to be a typeglob. File handles, such as 'FH' and 'FILE' in the two examples, are actually typeglobs. If you change the 'FH' to 'fh' below, it will fail with bareword construct warnings.

That being said, since typeglobs are global to the program, using 'local' will localize it to the subroutine (presuming that you're in one, of course), and protect any ones used globally.

The best way to do this, for other than quick'n'dirty stuff, is to use IO::Handle. Using a handle created with IO::Handle, you can pass the handle around as a scalar, not have to worry about namespace collision, etc.

If you have Advanced Perl Programming, chapter 3, talks about 'Perl Variables, Symbol Table, and Scoping', and section 4 talks about file handles explicitly.
#!/usr/local/bin/perl -w use strict; open (FH, ">myworld") || die $!; binmode FH; print FH "Hello, world\n"; close FH;
--Chris

e-mail jcwren

Replies are listed 'Best First'.
RE (tilly) 2 (why): Problem with Pack
by tilly (Archbishop) on Sep 23, 2000 at 13:08 UTC
    I use lexically scoped filehandles all of the time without ever digging into the IO::* family. The three basic techniques are to use Symbol and call gensym, construct your own symbol with do {local *FOO}, or use 5.6 which autovivifies handles for you.

    I generally am not on 5.6 so I tend to either use Symbol or do it myself. (Usually Symbol.)