FAQ 5.8 How can I make a filehandle local to a subroutine? How do I pass filehandles betw...

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


5.8: How can I make a filehandle local to a subroutine?  How do I pass
filehandles between subroutines?  How do I make an array of filehandles?

    As of perl5.6, open() autovivifies file and directory handles as
    references if you pass it an uninitialized scalar variable. You can then
    pass these references just like any other scalar, and use them in the
    place of named handles.

            open my    $fh, $file_name;

            open local $fh, $file_name;

            print $fh "Hello World!\n";

            process_file( $fh );

    If you like, you can store these filehandles in an array or a hash. If
    you access them directly, they aren't simple scalars and you need to
    give "print" a little help by placing the filehandle reference in
    braces. Perl can only figure it out on its own when the filehandle
    reference is a simple scalar.

            my @fhs = ( $fh1, $fh2, $fh3 );

            for( $i = 0; $i <= $#fhs; $i++ ) {
                    print "just another Perl answer, \n";

    Before perl5.6, you had to deal with various typeglob idioms which you
    may see in older code.

            open FILE, "> $filename";
            process_typeglob(   *FILE );
            process_reference( \*FILE );

            sub process_typeglob  { local *FH = shift; print FH  "Typeglob!" }
            sub process_reference { local $fh = shift; print $fh "Reference!" }

    If you want to create many anonymous handles, you should check out the
    Symbol or IO::Handle modules.


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in

Site Timeline