Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: passing filename in subroutines

by elusion (Curate)
on Mar 04, 2003 at 03:16 UTC ( [id://240225]=note: print w/replies, xml ) Need Help??


in reply to passing filename in subroutines

Are you trying to pass a filehandle to a subroutine? If so, there are a variety of methods you can use.

The first is, you can just not pass it. Filehandles are global. So you can just use it, like this:

sub foo { open FILE, "file.txt"; bar(); close FILE; } sub bar { my @lines = <FILE>; # do something here }
Second, you can open the filehandle as a variable and pass that. This is probably the best method.
sub foo { open my $file, "file.txt"; bar($file); close $file; } sub bar { my ($file) = @_; my @lines = <$file>; # do something here }
Lastly, I think you can use a typeglob. But I'm not sure how, and it'll be ugly. My advice would be to forget that I even mentioned it and use one of the other methods. But it's there if you need it.

elusion : http://matt.diephouse.com

Replies are listed 'Best First'.
Re: Re: passing filename in subroutines
by Hofmator (Curate) on Mar 04, 2003 at 11:36 UTC
    Lastly, I think you can use a typeglob. But I'm not sure how, and it'll be ugly.
    Depends on your definition of ugly ;-)

    It's not difficult either - taking up on your example:

    sub foo { local *FILE; open FILE, "file.txt"; bar(*FILE); } sub bar { my $file = shift; my @lines = <$file>; # do something here }

    Your alternative that's using the lexical variable as a filehandle is still the best, imho, but compared to not passing it and relying on the global variable, the typeglob approach is surely better - unless the script is very short and trivially simple. Btw, note my use of local to avoid clobbering the global filehandle FILE.

    -- Hofmator

Re: Re: passing filename in subroutines
by snam (Novice) on Mar 04, 2003 at 04:12 UTC
    thx^^

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://240225]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2024-03-28 11:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found