Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

What do I gain if I write to a real reference like \*STDOUT instead of a typeglob like *STDOUT?

like image 962
sid_com Avatar asked Dec 05 '22 16:12

sid_com


1 Answers

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
like image 54
DVK Avatar answered Dec 21 '22 23:12

DVK