J Krugman said:
Why is it that I find globs so mysterious? Am I alone in this?
Or is it a common thing?
Anyway, my question is this: what's the difference between $x, $y,
and $z in
my $x = *VAR;
Here, whoever gets hold on $x can access the package variables $VAR, @VAR,
%VAR, the filehandle and the sub VAR, plus more exotic stuff. The glob
refers to a live variable whose values you may or may not want overwritten.
Its purpose is to create an alias to one or more of the package variables.
This technique was sometimes useful in Perl 4 for parameter passing, but
is now obsolete. References do a better job.
Localizing the glob protects the original values of the associated package
variables, but assignments to @$y (say) still assign to @VAR, etc. After
leaving the scope of local(), the original values are restored. Within
the scope there are two different ways of accessing the same locations.
It can be used to produce an otherwise unused glob, usually for the
creation of a file handle. Within the scope of local, the filehandle
would be identical with the filehandle VAR. That's tolerable in a
small scope but is better avoided, in particular if VAR may be used
as a filehandle elsewhere in the program.
my $z = do { local *VAR };
The do-block takes care of that. Now the scope of local is the do-block,
so the glob in $z is essentially anonymous. The original values of
*VAR are unaffected. In particular, if VAR was an open filehandle, it
still is, and the glob in $z has nothing to do with it. It can be
opened to another file without interference.
Therefore, the common idiom to create a glob for a filehandle is
"do { local *VAR }". However, all this is now encapsulated in
the Symbol module and the various *::Handle modules, and ultimately
in open() itself with its autovivification of an undefined value
to a globref. It is rarely necessary to handle globs directly.
The evolution of "lexical filehandles" from typeglobs is an interesting
step. Much like natural evolution made an auditory ossicle from an
extra joint in the jaw (or whatever it was) that was no longer needed,
Perl exploits the fact that typeglobs are no longer needed for parameter
passing and uses them as filehandles.
And Perl's messy IO gets a little messier.
Anno