Tuesday, July 28, 2009

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...

How do I pass a file handle as a function parameter in perl?
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.





see http://www.davidpashley.com/articles/per...





for the clean way to get a handle as a variable, and then you pass it as you would pass any normal variable.
Reply: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 (%26lt;$fileHandle%26gt;)


{


my $line = $_;


chomp($line);


print "$line\n";


}


}





open(MYINPUTFILE, "%26lt;filename.in");


printFile(\*MYINPUTFILE);


close(MYINPUTFILE);
Reply: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, "%26lt;$file") or die("Error: Could not open $file");


@data = %26lt;FILE_IN%26gt;;


close(FILE_IN);

eurovision song contest

No comments:

Post a Comment