The same global name refers to multiple things in Perl. $x is a scalar, @x is an array, %x is a hash, &x is a subroutine, x is (when used in the correct location) a filehandle. The collection of all these senses for a name is stored in that symbol's typeglob. You can get at the typeglob using the `*' operator: *x is the typeglob of `x'.

Here are some ways you can use typeglobs:

  • *a = *b makes a an alias for b. Now %a and %b refer to the same hash, a and b to the same filehandle, etc.
  • *a = \@b is trying to assign a reference (in this case, an array ref) to *a. So it goes right into the array slot of a, so now @a is aliased to @b (but no alias has been created for other variables named `a'!). This also works for hash references and scalar references, of course, as well as code references.
  • $a = *B is the odd man out. It's trying to assign a typeglob to a scalar, which is impossible. Instead, $a gets the filehandle field of B -- print $a stuff will be the same as print B stuff. You can also use this form when passing arguments to a function; this is how passing a filehandle is done!
  • *a can be treated as a (read only, for boring reasons) hash containing fields containing references for that symbol's variables. These include SCALAR, ARRAY, HASH, CODE and FILEHANDLE. You also get the fields NAME and PACKAGE, which give the name and package of the symbol.
Typeglobs are weird. But they make for good fun, and are sometimes the way to go!

Note that my variables are completely different -- they're resolved by the compiler, and refer to no typeglob. This is unlike the so-called "local" variables, which are global variables whose value has been temporarily pushed onto a stack.

Log in or register to write something here or to contact authors.