This section provides a tutorial example on how to use hard references by replacing identifiers with reference scalar variables like, $$name.
As mentioned in the previous section,
if the hard reference of a variable or function is stored in a scalar variable, the scalar variable
can be directly placed in the place where the variable or function identifier should be.
The following tutorial program shows you some examples:
#- HardRef1.pl
#- Copyright (c) 1999 by Dr. Herong Yang, http://www.herongyang.com/
#
$foo = 0;
@foo = (0);
%foo = (k,0);
$refs = \$foo;
$refa = \@foo;
$refh = \%foo;
$reff = \&foo;
$$refs = 10; print "$foo\n"; # the scalar of $foo
@$refa = (20); print "$foo[0]\n"; # entire array of @foo
$$refa[0] = 30; print "$foo[0]\n"; # an element of @foo
@$refa[0] = (40); print "$foo[0]\n"; # a slice of @foo
%$refh = ('k',50); print "$foo{k}\n"; # entire hash of %foo
$$refh{'k'} = 60; print "$foo{k}\n"; # an element of %foo
@$refh{'k'} = (70); print "$foo{k}\n"; # a slice of %foo
&$reff(80); sub foo {print "$_[0]\n";} # calling &foo(80)
Here is the output of the tutorial program:
10
20
30
40
50
60
70
80
Please note that references take higher precedence that subscriptions: [], lookups: {},
and function calls: (). For example, $$refa[0] will be evaluated
$$refa fist, not $refa[0] first.