<> wrote:
> Here is a piece of code whose output is : 'miami21 and miami21' :
> #!/usr/bin/perl
> use strict ;
> my %hash = () ;
> push @{$hash{florida}}, 'miami', 'miami01', 'miami02' ;
> push @{$hash{florida}}, 'miami', 'miami21', 'miami22' ;
> my $name = ${$hash{florida}}[4] . " and " . $hash{florida}[4] ;
> print "name = $name \n" ;
> How are $hash{florida}[4] and ${$hash{florida}}[4] the same thing?
> I would have expected that indirection (I hope that is the correct
> word for it) to produce something unintelligible or something
> meaningless.
There's a special rule that '$hash{florida}[4]' is understood
to mean '$hash{florida}->[4]' and that's why you get the same
value as from '${hash{florida}}[4]'. The same holds if you have
a hash reference instead of an array reference, e.g. with
$hash{x} = { age => 7, name => 'Marvin };
print $hash{x}{age};
This will give you 7 since it's treated as if you had written
'$hash{x}->[age}' which is the same as ${$hash{x}}{age}'.
Or another example where there's a shortcut
$a = [ [ 1, 2, 3 ], [ 4, 6, 7 ] ];
print $b->[1][1];
will print 5 since it's taken to mean '$b->[1]->[1] or
${$b->[1]}[1]}' or '${$$b[1]}[1]' or '${${$b}[1]}[1]'
All this follows the same rule: the arrow operator is
optional between brackets and braces (or between a closing
bracket or brace and a paranthesis for an indirect function
call).
Most often it's probably used for "multidimensional arrays"
(I put that in parantheses since there aren't real multi-
dimensional arrays in Perl but instead you use arrays of
array references to emulate them). So when you have e.g.
@a = ( [ 1, 2, 3 ], [ 4, 5, 6 ] );
without that rule you would have to use one of
$a[1]->[1] or ${$a[1]}[1]
to get at the second element of the second array. But know
you can it write it instead as
$a[1][1]
which will make it look more like a normal multi-dimensional
array for people used to e.g. C.
Regards, Jens
--
\ Jens Thoms Toerring ___
\__________________________
http://toerring.de