5

Is it possible to send a file handle as an argument to a subroutine in PERL?

If yes, can you help with a sample code snippet showing how to receive it and use it in the subroutine?

aschultz
  • 1,658
  • 3
  • 20
  • 30
Daanish
  • 1,061
  • 7
  • 18
  • 29

3 Answers3

12

You're using lexical variables (open(my $fh, ...)) as you should, right? If so, you don't have to do anything special.

sub f { my ($fh) = @_; print $fh "Hello, World!\n"; }
f($fh);

If you're using a glob (open(FH, ...)), just pass a reference to the glob.

f(\*STDOUT);

Though many places will also accept the glob itself.

f(*STDOUT);
ikegami
  • 367,544
  • 15
  • 269
  • 518
6

Yes you can do it using .below is the sample code for the same.

#!/usr/bin/perl

use strict;
use warnings;

open (MYFILE, 'temp');

printit(\*MYFILE);

sub printit {
    my $fh = shift;
    while (<$fh>) {
        print;
    }
}

below is the test:

> cat temp
1
2
3
4
5

the perl script sample

> cat temp.pl
#!/usr/bin/perl

use strict;
use warnings;

open (MYFILE, 'temp');
printit(\*MYFILE);
sub printit {
    my $fh = shift;
    while (<$fh>) {
        print;
    } 
}

execution

> temp.pl
1
2
3
4
5
> 
Vijay
  • 65,327
  • 90
  • 227
  • 319
4

Yes, like this:

some_func($fh, "hello");

where some_func is defined like this:

sub some_func {
    my ($fh, $str) = @_;
    print { $fh } "The message is: $str\n";
}
melpomene
  • 84,125
  • 8
  • 85
  • 148