You need references. Everybody programming in Perl does, since they are one of the basics of the language. A bit like C’s pointers, references can be used to refer to all sorts of other things, including scalars, arrays, hashes, filehandles, typeglobs, subroutines, and synthetic data structures. If C calculates addresses and dereferences pointers with & and *, respectively, Perl does much the same with \ and $.
You need references. Everybody programming in Perl does, since they are one of the basics of the language. A bit like C’s pointers, references can be used to refer to all sorts of other things, including scalars, arrays, hashes, filehandles, typeglobs, subroutines, and synthetic data structures. If C calculates addresses and dereferences pointers with & and *, respectively, Perl does much the same with \ and $.
Why use references? First, they go great with subroutine calls. The usual way to pass an array or hash between a subroutine and its caller involves pushing around all the values of the array or hash. You can get the same or better results instead by passing just the single reference to the array or hash.
Also, references are necessary for complex data structures. The values of arrays and hashes must be scalars, so there’s no direct way to make hashes of hashes. However, references have the syntax of scalars, so you can make arrays of references to arrays of…. Before long, you’re writing code with variables like
$history{recent}[$western]{traffic}
Looking at References
Let’s look at an example. Suppose I want to have a “reverse chomp” operator that would add a newline to every element of an array. I could write the code as follows:
for $element (@array) { $element .= “n”; }
And while this would certainly work, it locks me into a specific variable named @array. If I wanted…
Please log in to view this content.
Not Yet a Member?
Register with LinuxMagazine.com and get free access to the entire archive, including: