Tuesday, September 11, 2007

Shortcuts with the Arrow Notation

Perl provides an alternate and easier-to-read syntax for accessing array or hash elements: the ->[ ] notation. For example, given the array's reference, you can obtain the second element of the array like this:
$rarray = \@array;
print $rarray->[1] ; # The "visually clean" way
instead of the approaches we have seen earlier:
print $$rarray[1]; # Noisy
#or
print ${$rarray}[1];

Similarly, you can use the ->{ } notation to access an element of a hash table:
$rhash = \%hash;
print $rhash->{"k1"};
#instead of ........
print $$rhash{"k1"};
# or
print ${$rhash}{"k1"};

No comments: