Array reference
am 26.12.2007 12:04:56 von vijay$VAR = [ [ '04', '01' ], 1 ];
how do i print "04" without using any temp variables?
$VAR = [ [ '04', '01' ], 1 ];
how do i print "04" without using any temp variables?
On Wed, 26 Dec 2007 03:04:56 -0800 (PST), "vijay@iavian.com"
>$VAR = [ [ '04', '01' ], 1 ];
>
>how do i print "04" without using any temp variables?
print $VAR->[0][0]; # perldoc perlref
Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^
vijay@iavian.com wrote:
> $VAR = [ [ '04', '01' ], 1 ];
>
> how do i print "04" without using any temp variables?
One way:
print $VAR->[0][0];
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
another way is.
${$VAR}[0][0]
or slightly shorter
$$VAR[0][0]
A bit of explanation to all the suggested solutions:
Remember how you subscript a regular array: $array[0].
If you have a reference to an array instead of a simple array, you can
just replace 'array' with your reference, which gives you $
$RefToArray[0].
To be sure that you don't get into precedence problems, you can also
write ${$RefToArray}[0]. That's because "anywhere you'd put an
alphanumeric identifier as part of a variable or subroutine name, you
can replace the identifier with a block returning a reference of the
correct type." [quoted from "Programming Perl"]
An alternative syntax to $$RefToArray[0] (i.e. syntactic sugar) is to
use the -> operator as in $RefToArray->[0]. The left operand of ->
must be a reference to an array/hash. The right is an array/hash
subscript (never slice). Thus you could even also write ($RefToArray)-
>[0].
Putting this together for your case, where the you have a reference to
an array of references: To get the '04', you want to subscript the the
reference to the inner array, which is given by, as learned above,
$VAR->[0] (or $$VAR[0] or ${$VAR}[0] ). Subscripting is always of the
form $...[...], thus, in a first version, you get ${$VAR->[0]}[0]. If
you use the syntax sugar notation, you get ($VAR->[0])->[0], or
without the superfluous parentheses $VAR->[0]->[0]. (or $$VAR[0]->[0]
or ${$VAR}[0]->[0]). To be honest, I don't know why exactly the
parentheses are superfluous, I strongly assume because of operator
precedence/associativity rules.
The second -> is optional too, so you get the shorter $VAR->[0][0] (or
$$VAR[0][0] or ${$VAR}[0][0]) as suggested by Gunnar and Michele. To
quote Programming Perl again: "The arrow is optional between brackets
or braces, or between a closing bracket or brace and a parenthesis for
and indirect function call"
Flo