How do I pass a file handle as a function parameter in perl?
I tried $FP = shift, but it didn't work...at least I don't think it did...
- 1 decade agoBest 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.
- timespiralLv 41 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:
my $fileHandle = $_;
my $line = $_;