Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send file handle as argument in perl

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?

like image 816
Daanish Avatar asked Nov 30 '22 13:11

Daanish


2 Answers

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);
like image 50
ikegami Avatar answered Dec 20 '22 13:12

ikegami


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
> 
like image 36
Vijay Avatar answered Dec 20 '22 12:12

Vijay