ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
3.3 Typeglobs and ReferencesYou 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 AliasingEarlier, we saw how a statement like *b = *a makes everything named " *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 ConstantsWe 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 SubroutinesWe 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 TypeglobsWe 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. |