sid_com sid_com - 2 years ago 74
Perl Question

Perl typeglobs and Real References: What do I gain if I write to \*STDOUT instead of *STDOUT?

What do I gain if I write to a real reference like

instead of a typeglob like

Answer Source

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:

$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";


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download