What do I gain if I write to a real reference like \*STDOUT
instead of a typeglob like *STDOUT
?
One is a typeglob, another is a reference to it.
As far as I know, the main practical difference is that you can NOT bless a typeglob into an object, but you CAN bless the typeglob reference (which is what IO::Handle
does)
This distinction is discussed in detail in "Perl Cookbook", Recipe 7.16. "Storing Filehandles in Variable".
Another difference is that assigning a glob creates an alias to the ENTIRE glob, whereas assigning a glob reference does the expected (as discussed in perldoc perlmod, "Symbol Tables" section
. To illustrate:
@STDOUT=(5);
$globcopy1 = *STDOUT; # globcopy1 is aliased to the entire STDOUT glob,
# including alias to array @STDOUT
$globcopy2 = \*STDOUT; # globcopy2 merely stores a reference to a glob,
# and doesn't have anything to do with @STDOUT
print $globcopy1 "TEST print to globcopy1/STDOUT as filehandle\n";
print "TEST print of globcopy1/STDOUT as array: $globcopy1->[0]\n\n";
print $globcopy2 "TEST print to globcopy2/STDOUT as filehandle\n";
print "TEST print of globcopy2/STDOUT as array: $globcopy2->[0]\n\n";
Produces:
TEST print to globcopy1/STDOUT as filehandle
TEST print of globcopy1/STDOUT as array: 5
TEST print to globcopy2/STDOUT as filehandle
Not an ARRAY reference at line 8.
As a side note, a rumor that the typeglob reference is the only way to pass the filehandle into a function is not the case:
sub pfh { my $fh = $_[0]; print $fh $_[1]; }
pfh(*STDOUT, "t1\n");
pfh(\*STDOUT, "t2\n");
# Output:
# t1
# t2
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