What's the difference between this code:
sub createOutputFile {
my $filepath = shift;
open my $fh, '>', $filepath;
return $fh;
and when last line is returned as refference return \$fh?
I know that $fh exists in local scope of createOutputFile subroutine, but what's returned when I'm not using reference? And as long as I'm creating output files using different filepaths, would I get some problems when I'd use reference?
If you return a reference, you'll get a reference. It means
print $ref
would return
REF(0x600077f10)
And you'll need to dereference it to get the file handle. It wouldn't disappear after leaving the subroutine, as there's still a reference pointing to it: the one you return (given you assign it to a variable). As you probably know, Perl uses reference counting, so the file handle won't be garbage collected until there's no reference to it.
Note that you can't use dereference in the diamond operator (it gets interpreted as a glob), so you have to use a variable
my $fh = $$fh_ref;
while (<$fh>) {
or call readline directly
while (readline $$fh_ref) {
The filepath is totally unrelated to how you return a file handle.
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