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?
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);
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
>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With