Advanced Perl Programming

Advanced Perl ProgrammingSearch this book
Previous: 3.2 TypeglobsChapter 3
Typeglobs and Symbol Tables
Next: 3.4 Filehandles, Directory Handles, and Formats
 

3.3 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.

3.3.1 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.

3.3.2 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."

3.3.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 also similarly give a name to other types of references.

3.3.4 References to Typeglobs

We have seen how references and typeglobs are equivalent (in the sense that references can be assigned to typeglobs). Perl also allows you to take references to typeglobs by prefixing it with a backslash as usual:

$ra = \*a;

References to typeglobs are not used much in practice, because it is very efficient to pass typeglobs around directly. This is similar to the case of ordinary scalars, which don't need references to pass them around for efficiency.


Previous: 3.2 TypeglobsAdvanced Perl ProgrammingNext: 3.4 Filehandles, Directory Handles, and Formats
3.2 TypeglobsBook Index3.4 Filehandles, Directory Handles, and Formats