Oh my Glob!
Last day I was seeking for an old program of mine, something I remember I wrote in Perl when I was a very baby-Perl programmer (today is much different, I’m a child Perl programmer!).Long story short: I did not find (yet) such program, but in the meantime I found this ancient and embarassing script I wrote pretty much 20 years ago. I don’t even remember why did I had to write such a stupid program, I guess I was experimenting with something more powerful of the Unix Shell back at that time.
Anyway, the program had a couple of lines that get my attention:
open(FILE,">>".$HOST_FILE) || ($FILE = 0);
if( $FILE == 0 ){
warn("\nWriting to stdout (maybe you don't have permissions to open $HOST_FILE?)\n");
*FILE = *STDOUT;
}
# ... much more code later ...
print FILE "\n$address $host $relative_host\t# automatically added by addHostsEntry.pl";
I was using typeglob assignment, poor me little bastard!
Essentially, the line
*FILE = *STDOUT;
is assigning to the typeglob FILE
the same thing as the global typeglob STDOUT
, that means that FILE
is a synonim for STDOUT
, with the latter being the standard output (i.e., the console).
That was ancient Perl, since thanks to the reference machinery, typeblogs can be pretty much avoided unles you need to do some sort of black magic (like aliasing a symbol table, importing or overriding methods, and so on). The documentation clearly states it:
% perldoc perldata
...
Another use for typeglobs is to pass filehandles into a function or to
create new filehandles. If you need to use a typeglob to save away a
filehandle, do it this way:
$fh = *STDOUT;
or perhaps as a real reference, like this:
$fh = \*STDOUT;
So yes, that were two errors in a row!