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 symbolic references by replacing identifiers with any string expressions, like ${EXPR}.

As mentioned in the previous section, if a variable or function identifier is presented by a string expression, the string expression can be placed in curly brackets {} to replace the identifier. Curly brackets are also called lookups. String literals in lookups don't have to be quoted.

The following tutorial program shows you some interesting examples. In the first group, I used scalar variables in the lookups. In the second group, I used some string literals and expressions in the lookups. In the third group, I used array elements, hash elements and function returns in the lookups.

#- SoftRef2.pl
#- Copyright (c) 1999 by Dr. Herong Yang, http://www.herongyang.com/
#
   $name = 'foo';
   @name = ('foo');
   %name = ('i', 'foo');
   
   ${$name} = 10; print "$foo\n";           # the scalar of $foo
   @{$name} = (20); print "$foo[0]\n";      # entire array of @foo
   ${$name}[0] = 30; print "$foo[0]\n";     # an element of @foo
   @{$name}[0] = (40); print "$foo[0]\n";   # a slice of @foo
   %{$name} = ('k',50); print "$foo{k}\n";  # entire hash of %foo
   ${$name}{'k'} = 60; print "$foo{k}\n";   # an element of %foo
   @{$name}{'k'} = (70); print "$foo{k}\n"; # a slice of %foo
   &{$name}(80);                            # calling &foo

   ${foo} = 110; print "$foo\n";           
   @{'foo'} = (120); print "$foo[0]\n";    
   ${"foo"}[0] = 130; print "$foo[0]\n";   
   @{'f'.'oo'}[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"; 
   &{'f'.'oo'}(180);                          

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

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

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

Using Symbolic References

$$name - Replacing Identifiers by Scalar Variables

${EXPR} - Replacing Identifiers by Expressions

EXPR->* - The Dereference Operator

$$$name - Nested Symbolic References

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