Typeglobs and References

You might have noticed that both typeglobs and references point to values. A variable $a can be seen simply as a dereference of a typeglob ${*a}. For this reason, Perl makes the two expressions ${\$a} and ${*a} refer to the same scalar value. This equivalence of typeglobs and ordinary references has some interesting properties and results in three useful idioms, described here.

Selective Aliasing

Earlier, we saw how a statement like *b = *a makes everything named "a" be referred to as "b" also. There is a way to create selective aliases, using the reference syntax:

*b = \$a;     # Assigning a scalar reference to a typeglob

Perl arranges it such that $b and $a are aliases, but @b and @a (or &b and &a, and so on) are not.

Constants

We get read-only variables by creating references to constants, like this:

*PI = \3.1415927;
# Now try to modify it.
$PI = 10;

Perl complains: “Modification of a read-only value attempted at try.pl line 3.”

Naming Anonymous Subroutines

We will cover anonymous subroutines in the next chapter, so you might want to come back to this example later.

If you find it painful to call a subroutine indirectly through a reference (&$rs()), you can assign a name to it for convenience:

sub generate_greeting {
     my ($greeting) = @_;
		sub { print "$greeting world\n";}
}
$rs = generate_greeting("hello");
# Instead of invoking it as &$rs(), give it your own name.
*greet = $rs;
greet();    # Equivalent to calling &$rs(). Prints "hello world\n"

Of course, you can ...

Get Advanced Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.