Passing Filehandles

To pass filehandles to subroutines, use the *FH or \*FH notations. These are "typeglobs"--see perldata/"Typeglobs and Filehandles" and especially perlsub/"Pass by Reference" for more information.

Here's an excerpt:

If you're passing around filehandles, you could usually just use the bare typeglob, like *STDOUT, but typeglobs references would be better because they'll still work properly under use strict 'refs'. For example:

    splutter(\*STDOUT);
    sub splutter {
        my $fh = shift;
        print $fh "her um well a hmmm\n";
    }
    $rec = get_rec(\*STDIN);
    sub get_rec {
        my $fh = shift;
        return scalar <$fh>;
    }
If you're planning on generating new filehandles, you could do this:

    sub openit {
        my $path = shift;
        local *FH;
        return open (FH, $path) ? *FH : undef;
    }
    $fh = openit('< /etc/motd');
    print <$fh>;


Back to perlfaq7