Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

how to pass filehandle between module ?

by bh_perl (Monk)
on May 11, 2013 at 02:27 UTC ( #1033077=perlquestion: print w/replies, xml ) Need Help??

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

hi

i have main perl program called main.pl. The program will called openfile module to open/create new output file and writefile module to write contents into output files.

But how could i write all the contents into output files in writefile module ?. My sample program as below:

This is MAIN.PL

#!/usr/bin/perl use lib '/tmp/bh'; use openFile qw/openfile/; use writeFile qw /writefile/; openfile; writefile; close (TEST);

This is openfile module

package openFile; use base 'Exporter'; our @EXPORT_OK = qw/openfile/; sub openfile { open (TEST, ">/tmp/bh/output/test.txt"); print (TEST "FILE HEADER\n"); } 1;

This is writefile module

package writeFile; use base 'Exporter'; our @EXPORT_OK = qw/writefile/; sub writefile { printf (TEST "This is for testing only\n"); } 1;

Replies are listed 'Best First'.
Re: how to pass filehandle between module ?
by Athanasius (Archbishop) on May 11, 2013 at 02:52 UTC

    It is possible to do what you want by making TEST a package-scope variable within package openFile and then exporting it. (You would also need to export an openFile::close() subroutine to call in place of close (TEST).)

    But this is a poor design. Much better to put all the file opening, writing, and closing routines together into a single package, e.g. package MyFile, and keep the details of the filehandle variable (in this case, MyFile::TEST) private to the package (i.e., unexported).

    The general rule of modularisation is: Group related things together and keep independent things separate. In this case, opening and writing to the file are closely related activities and should be implemented within the same package.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: how to pass filehandle between module ?
by vsespb (Chaplain) on May 11, 2013 at 13:40 UTC
Re: how to pass filehandle between module ? (like a variable)
by Anonymous Monk on May 11, 2013 at 08:11 UTC

    Filehandles are variables, so to pass a filehandle between modules, pass it like a variable, see perlintro for the details

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2023-02-01 15:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (10 votes). Check out past polls.

    Notices?