Anonymous asked in Computers & InternetProgramming & Design · 1 decade ago

How do I pass a file handle as a function parameter in perl?

I tried $FP = shift, but it didn't least I don't think it did...

4 Answers

  • 1 decade ago
    Best Answer

    that would do it , if it was inside a sub and you didn't care about keeping the parameters for the rest of the sub.

    make sure you get the handle the right way.


    for the clean way to get a handle as a variable, and then you pass it as you would pass any normal variable.

  • trish
    Lv 4
    3 years ago

    Perl File Handler

  • 1 decade ago

    I think it's best not to keep a file handle open for long. Things hapen... like program hang or computer reboots while program running. The longer the file handle is open the more uncertainty there is as to what happens to your data file. If you're not dealing with huge amounts of data just slurp all of it into a variable. I usually put it in an array like this

    open(FILE_IN, "<$file") or die("Error: Could not open $file");

    @data = <FILE_IN>;


  • 1 decade ago

    The above is valid and arguably a "better" but heavier way to handle file IO, but the simple answer is to pass a reference... Example below:

    sub printFile($)


    my $fileHandle = $_[0];

    while (<$fileHandle>)


    my $line = $_;


    print "$line\n";



    open(MYINPUTFILE, "<");



Still have questions? Get your answers by asking now.