Perl Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 5.00

${EXPR} - Replacing Identifiers by Expressions

This section provides a tutorial example on how to use hard references by replacing identifiers with any expression that returns hard references, like ${EXPR}.

As mentioned in the previous section, if the hard reference of a variable or function is represented by an expression, the expression can be placed in curly brackets {} to replace the variable or function identifier.

The following tutorial program shows you some interesting examples. In the first group, I used scalar variables that contain hard references in the lookups. In the second group, I used hard references directly in the lookups. In the third group, I used an array to store the hard references.

#- HardRef2.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;
   @refl = (\$foo, \@foo, $refh, $reff);
   
   ${$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);                            # calling &foo

   ${\$foo} = 110; print "$foo\n";           
   @{\@foo} = (120); print "$foo[0]\n";    
   ${\@foo}[0] = 130; print "$foo[0]\n";   
   @{\@foo}[0] = (140); print "$foo[0]\n";   
   %{\%foo} = ('k',150); print "$foo{k}\n";
   ${\%foo}{'k'} = 160; print "$foo{k}\n"; 
   @{\%foo}{'k'} = (170); print "$foo{k}\n"; 
   &{\&foo}(180);                          

   ${$refl[0]} = 210; print "$foo\n";       
   @{$refl[1]} = (220); print "$foo[0]\n";
   ${$refl[1]}[0] = 230; print "$foo[0]\n";    
   @{$refl[1]}[0] = (240); print "$foo[0]\n";
   %{$refl[2]} = ('k',250); print "$foo{k}\n";
   ${$refl[2]}{'k'} = 260; print "$foo{k}\n";
   @{$refl[2]}{'k'} = (270); print "$foo{k}\n";
   &{$refl[3]}(280);                       

sub foo {print "$_[0]\n";}

Here is the output of the tutorial program:

10
20
30
40
50
60
70
80
110
120
130
140
150
160
170
180
210
220
230
240
250
260
270
280

Sections in This Chapter

\* - Creating Hard References

Using Hard References

$$name - Replacing Identifiers by Scalar Variables

${EXPR} - Replacing Identifiers by Expressions

EXPR->* - The Dereference Operator

$$$name - Nested Hard References

\$b-\$a - Using Hard References in Other Operations

Dr. Herong Yang, updated in 2008
${EXPR} - Replacing Identifiers by Expressions