|
Once you have created a reference, you
will need to get at the value that the reference holds. However,
recall that references hold "pointers" to memory slots. So if you
simply access the value of the reference, you probably won’t get
what you want.
Consider the following case:
#!/usr/local/bin/perl
$my_scalar = "Selena Sol";
@my_array = ("1", "2", "3");
$scalar_reference = \$my_scalar;
$array_reference = \@my_array;
print "$scalar_reference\n" .
"$array_reference\n";
Check out the results! Notice that for
$scalar_reference, Perl prints out the odd looking value
"SCALAR(Ox1011e9e8)" instead of "Selena Sol".
Well, Perl is doing the requested thing, of course and
printing out the value of the reference that corresponds to a location
in memory where the contents of $my_scalar are actually held.
Of course, it is most likely that what you really
want is the value the reference is pointing to. Well, to get this value,
you must "dereference" the reference.
Dereferencing scalar, array, hash and subroutine
references follow a very similar pattern as exemplified below:
#!/usr/local/bin/perl
$my_scalar = "Selena Sol";
@my_array = ("1", "2", "3");
%my_hash = {‘name => ‘Gunther’,}
$scalar_reference = \$my_scalar;
$array_reference = \@my_array;
$hash_reference = \%my_hash;
print "$$scalar_reference\n" .
"@$array_reference[0]\n" .
"$hash_reference->{‘name'}\n";
Notice that we use an extra $ and @ in the
case of dereferencing scalars and arrays, and that we use the ->
for hashes. Check out the results of this little program:
Finally, a subroutine reference can be dereferenced
using an "&" before the reference name such as:
#!/usr/local/bin/perl
sub printMessage
{
my ($string) = @_;
print "$string\n";
}
$subroutine_reference = \&printMessage;
&$subroutine_reference("Hello Cyberspace");
Previous |
Next |
Table of Contents
|