perl filehandles question

Hi,

Is there a way, in perl, to pass a file handle to multiple subroutines while still using the same file handle in the 'main' section of the program.

this does not appear to be working.

Code:
  open(FH,"<a_file") or die $!;
   while(my $line =<FH>){
           .
           .
   <some processing>
   }

  &sub_routine_A(*FH);
  &sub_routine_B(*FH);
 
Try passing it by reference instead of by value.

Code:
use strict;
use FileHandle;

my $fh = FileHandle->new("a_file","r");

while( ! $fh->eof() ) {
 my $line = $fh->getline();
 ...
 ...
}

&sub_routine_A(\$fh); # \$fh is a reference to $fh
 
If you are not on a rather old version of Perl then you may simply use a my (local) variable as a file handle (instead that old-school FH handle and typeglobbing). This can also easily be passed as an argument:
Code:
#!/usr/bin/perl

use strict;

sub proc_file
{
    my $handle = shift;
    while(<$handle>)
    {
        print;
    }
}

open(my $fh, "<", "fharg.pl");
proc_file($fh);
close($fh);
Here the filehandle $fh was created in the main program and passed as an argument to proc_file() subroutine.
 
Back
Top