Using the lexical form, as has already been mentioned, is considered better by most monks it appears (and I agree). However, to answer your literal question, the answer is "yes". Yes, it's global (though in your package). Other subroutines can use it as-is, calling it "FILEHANDLE". That, of course, means that if a subroutine opens another file using the FILEHANDLE glob, well, you run into problems. This is why you should always localise your filehandles before use - it doesn't prevent someone else from stepping on your filehandle, but it does prevent you from stepping on someone else's filehandle. If everyone does that, then there ends up being no squashing of handles.
Next question is also a "yes" - it's possible. In fact, there are two ways. First is to take advantage of the fact that when you use "FILEHANDLE" with no sigil, it's treated as a bareword. And since there's no function by the name "FILEHANDLE" (all upper-case subs are frowned upon except as constants, so we should be ok here), perl treats it as the string "FILEHANDLE" Then it uses that string as the name of the variable to populate. Sneakily, it treats it as if it were in the caller's package space, so if you pass a string with the name of the handle to another package, you'll have to construct it fully, e.g.:
This is the bad way of doing it. The second option is to use a reference to the real variable: *FILEHANDLE. So you can call a function like this: Foo::handle(\*FILEHANDLE) or, in my example:#!/usr/bin/perl use strict; use warnings; Foo::handle(__PACKAGE__ . '::DATA'); package Foo; sub handle { my $handle = shift; my $data = join '', <$handle>; print $data; } __END__ Some text Blah blah
Note that all the localisation requirements still hold with these - if Foo::handle were to open a new handle using your ::FILEHANDLE (directly or indirectly), it would still quash the filehandle it was working with. Better to use lexical variables. (I don't think you can use lexical variables with DATA, but that's probably ok, since it's a built-in and I doubt anyone would use that handle for anything else.)#!/usr/bin/perl use strict; use warnings; Foo::handle(\*DATA); package Foo; sub handle { my $handle = shift; my $data = join '', <$handle>; print $data; } __END__ Some text Blah blah
In reply to Re: Sending filehandles?
by Tanktalus
in thread Sending filehandles?
by tamaguchi
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |