Shall we dance, sweet reference?
March 13, 2000
You now command two vital pieces of knowledge for working with
Perl references: how to construct a reference, and how to
dereference. Like learning how to juggle a hackeysack with your
ankle, the question becomes clear: why do I want to do this
anyway? What are these references good for?
The trick is, you've already used them, if you followed along
last month's installment working with complex lists and hashes.
In that article, we relied on anonymous references to construct
nested lists and hashes. An anonymous reference is simply a
reference that points to explicit data rather than a containing
variable; for instance:
$days=["monday","tuesday","wednesday"];
Here, the reference $days points directly to the values
listed, without being bound to an intermediary variable. We used
this type of anonymous reference, for example, when we nested a
list into a list:
push(@carmodels,["sentra,stanza,altima"]);
Similarly, you can create a reference that points to an anonymous
hash:
$grades={"Tom Jones"=>92,"Briget
Gidget"=>85};
It's very important to distinguish the above, where $grades
is a reference pointing to a hash, from a "real"
hash, which would not use the curly braces in its definition
but rather parentheses. Thus, to access the value for the key
"Tom Jones" in the anonymous hash, you'd use
dereferencing syntax:
print $grades->{"Tom Jones"};
Now, let's twist. Because a reference can be treated as a scalar
variable, you can use a reference in many places where you would
use a scalar; for instance, a reference can be the value of a
list item, or the value of a hash key. Keep the $grades
reference in mind as we two-step through the following examples:
@class=("Physics 101","Exam
1",$grades);
The third item in the list @class is now the reference
$grades, which points to the anonymous hash seen previously.
To access "Tom Jones" from this list:
print @class[2]->{"Tom Jones"};
Similarly, you can use a reference as the value of a hash key,
but you cannot use a reference as a key of a hash.
%roster=("class"=>"Physics
101","exam"=>1,"grades"=>$grades);
print $roster{"grades"}->{"Tom Jones"};
Dereference, my dear
The Perl You Need to Know
Take my Parameters, Please
|