STDOUT is a "bareword filehandle". Bare-words are discouraged because they introduce a potential source for bugs. Watch this:
use strict;
use diagnostics;
sub myprint {
my( $fh, $text ) = @_;
print $fh $text;
}
myprint( STDOUT, "Hello world!\n" );
This will produce the following:
Bareword "STDOUT" not allowed while "strict subs" in use at mytest.pl
+line 15.
Execution of mytest.pl aborted due to compilation errors (#1)
(F) With "strict subs" in use, a bareword is only allowed as a
subroutine identifier, in curly brackets or to the left of the "=>
+"
symbol. Perhaps you need to predeclare a subroutine?
Uncaught exception from user code:
Bareword "STDOUT" not allowed while "strict subs" in use at mytest
+.pl line 15.
Execution of mytest.pl aborted due to compilation errors.
...which is a pretty good explanation; barewords introduce an ambiguity. Watch this:
use strict;
use diagnostics;
sub myprint {
my( $fh, $text ) = @_;
print $fh $text;
}
sub STDOUT {
print "Woops!\n";
}
myprint( STDOUT, "Hello world!\n" );
...which produces...
Woops!
Can't use string ("1") as a symbol ref while "strict refs" in use at m
+ytest.pl
line 8 (#1)
(F) You've told Perl to dereference a string, something which
use strict blocks to prevent it happening accidentally. See
"Symbolic references" in perlref. This can be triggered by an @ o
+r $
in a double-quoted string immediately before interpolating a varia
+ble,
for example in "user @$twitter_id", which says to treat the conten
+ts
of $twitter_id as an array reference; use a \ to have a literal @
symbol followed by the contents of $twitter_id: "user \@$twitter_i
+d".
Uncaught exception from user code:
Can't use string ("1") as a symbol ref while "strict refs" in use
+at mytest.pl line 8.
main::myprint(1, 'Hello world!\x{a}') called at mytest.pl line 15
What's going on is a little nuanced. First a subroutine named STDOUT is executed, printing "Woops!\n". The return value is the return value of print, which is '1' if it was successful. It was successful, because it successfully printed "Woops!\n". That '1' is now treated as a symbolic reference, which is obviously not what you want.
Now let's clean things up:
use strict;
use diagnostics;
sub myprint {
my( $fh, $text ) = @_;
print $fh $text;
}
sub STDOUT {
print "Woops!\n";
}
myprint( \*STDOUT, "Hello world!\n" );
This prints "Hello world!", which is probably what we wanted all along. In this case, we're explicitly passing a reference to the typeglob *STDOUT, which is a filehandle. It doesn't matter that there's a subroutine named &STDOUT, because &STDOUT is a different entity from *STDOUT, and our chosen syntax disambiguates this for Perl.