Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

File handle as argument

by palette (Scribe)
on Jun 03, 2005 at 06:28 UTC ( [id://463125]=perlquestion: print w/replies, xml ) Need Help??

palette has asked for the wisdom of the Perl Monks concerning the following question:

Hi all
Can i send a file handle as a argument to a subroutine
eg:
Consider I have a file called /xxx/abc.txt
open(IN,'/xx/abc.txt');
can i have this file handle (anyway it is just like a array or scalar reference :) i think that filehandle is going to be a reference if wrong please correct me) passed as argument to a subroutine. If i can pass it as an argument please mention how to implement it. Please guide me if i am wrong and explain in what way a file handle is actually internally manipulated in Perl.
Thankyou

Replies are listed 'Best First'.
Re: File handle as argument
by bobf (Monsignor) on Jun 03, 2005 at 07:28 UTC

    If you open a file using a filehandle, you can create a reference to it (by creating a reference to the typeglob) and then pass the reference to subs:

    open( FH, '>', $filename ) or die $!; my $ref2fh = \*FH; foo( $ref2fh );

    My preferred method, though, is to open the file using a lexical variable (which eliminates the typeglob business):

    open( my $fh, '>', $filename ) or die $!; foo( $fh );

    See the section entitled "File and directory handles can be autovivified" in perldelta for perl 5.6 for more info on opening files using scalar variables (perl56delta on CPAN). This info is also in perlopentut under "Indirect Filehandles".

    HTH

    Update: added a link for perldelta

Re: File handle as argument
by spurperl (Priest) on Jun 03, 2005 at 06:41 UTC
    It can be done with and without references.

    Without references: use globs like this - foo(*FH). Then in "foo" you just use my $fh = shift; And $fh can be plugged in like a file-handle, in "print", for example.

Re: File handle as argument
by PodMaster (Abbot) on Jun 03, 2005 at 06:32 UTC
    Sure. `perldoc perlsub' deals with subroutines. It goes somethig like
    foo(\*HANDLE);

    MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
    I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
    ** The third rule of perl club is a statement of fact: pod is sexy.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-20 01:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found