Dereference, my dear
March 13, 2000
Return with us to our simple example:
$name="Moe";
$name_reference=\$name;
Merrily we stroll along, and attempt to print out the value that
this reference points to:
print $name_reference;
Yields:
SCALAR(0xba5e84)
Ack! What is that? Gibberish, but let's look at it from Perl's
perspective:
$name_reference is a pointer to what? It's a pointer to
a scalar variable, which is exactly what Perl reports when we
try to output the value of $name_reference. As humans,
we don't want to know this, we want to know the value of the
variable which $name_reference points to. A-ha! That
my dear is called dereferencing. Whereas creating a
reference builds the pointer, dereferencing follows the pointer
to access its end value.
The simplest way to dereference a reference, especially a
reference that points to a scalar variable, is to precede
the reference with a dollar sign. Yes, that means dual dollar
signs:
print $$name_reference;
Yields:
Moe
Looks funny, but it works. Dereferencing is very simple when
your reference points to a scalar variable. Things get a little
more complicated when the references leads to a list or a hash.
Let's consider. You can dereference a list for two different
yields: you may wish to access a single element of the list, or
you may wish to access the list as a whole. First, let's create
a list and a reference to it:
@wingsauces=("mild","medium","hot");
$wingsauce=\@wingsauces;
We can use the reference to pluck the first item from the list:
print ${$wingsauce}[0];
or
print $wingsauce->[0];
The above syntaxes are equivalent and yield the same result, in
this case, "mild".
We can also use the reference to grab the whole list and work
with it in a list context:
print join(",",@{$wingsauce});
Here, the join() function is used to demonstrate the
list context; this function takes a list and joins the elements
using the given character (here, a comma); you can see that we
dereference the whole list using the @{ } construction,
placing the dereference variable $wingsauce within the
curly braces.
When dereferencing a hash, the syntax is a little different
but no more complicated.
%mandms=("red"=>25,"brown"=>15,"blue"=>40);
$mmhash=\%mandms;
print $mmhash->{"blue"};
Yields:
40
The arrow constructor is used to dereference a particular key
of a hash. Here, we dereference the key "blue". For
some heartier acrobatics, let's use a dereference to pull out
the keys of the hash %mandms:
print keys %{$mmhash}
Not bad at all! The keys function requires a hash, which we
provide with the % prefix, within whose curly braces we specify
the reference scalar, $mmhash.
Works like a charm indeed.
The Perl You Need to Know Part 11: A Reference of References
The Perl You Need to Know
Shall we dance, sweet reference?
|