# perl filehandles question



## Business_Woman (Oct 12, 2012)

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.


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

  &sub_routine_A(*FH);
  &sub_routine_B(*FH);
```


----------



## SirDice (Oct 12, 2012)

Try passing it by reference instead of by value.


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


----------



## izotov (Oct 12, 2012)

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:

```
#!/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.


----------



## Business_Woman (Oct 12, 2012)

Hm, seems like Perl closes the file handle after the first subroutine returns.


----------

