2011年10月21日 星期五

dynamically allocated scalars

What about dynamically allocated scalars ? It turns out that Perl doesn't have any notation for doing
something like this, presumably because you almost never need it. If you really do, you can use the
following trick: Create a reference to an existing variable, and then let the variable pass out of scope.
{
    my $a = "hello world";  # 1
    $ra = \$a;              # 2 
}
print "$$ra \n";            # 3
The my operator tags a variable as private (or localizes it, in Perl-speak). You can use the local operator
instead, but there is a subtle yet very important difference between the two that we will clarify in Chapter
3. For this example, both work equally well.
Now, $ra is a global variable that refers to the local variable $a (not the keyword local). Normally, $a
would be deleted at the end of the block, but since $ra continues to refer to it, the memory allocated for $a
is not thrown away. Of course, if you reassign $ra to some other value, this space is deallocated before $ra
is prepared to accept the new value.
You can create references to constant scalars like this:
$r = \10;  $rs = \"hello";
Constants are statically allocated and anonymous.
A reference variable does not care to know or remember whether it points to an anonymous value or to an
existing variable's value. This is identical to the way pointers behave in C.

沒有留言:

張貼留言