Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monks please forgive my lack of knowledge in this matter:
I have an array reference with only one value in it (this is from inherited code).
It seems silly to run a loop in this manner:
foreach( @$res ) { print "$_->[0]\n"; }
when in this case there is only one row/value to pull out. going the loop route obvioulsy works, but I would think that you should be able to do this in a one-liner so I did this:
print "$res->[0]\n";
But got this result instead:
ARRAY(0x1bcfa60)
The is apparently some subtle piece of wisdom that I am missing. Any help that you can provide is greatly appreciated. Thanks in Advance!

Replies are listed 'Best First'.
Re: Array Deferencing Question
by davido (Cardinal) on Oct 01, 2004 at 16:09 UTC

    The subtile piece of wisdom is that you are dealing with an array of arrays. In other words, it's two levels deep. You would dereference it like $res->[0][0], for example.


    Dave

Re:Array Deferencing Question
by ikegami (Patriarch) on Oct 01, 2004 at 16:15 UTC

    foreach is often used with single element as a convenient method of both setting $_ and providing a block in which last can be used.

    As for your problem, the code is equivalent to:

    foreach --+ +-- first iteration | | v v print( (@$res)[0]->[0], "\n"); ---------- | +-- What $_ contained

    or just:
    print "$res->[0][0]\n";

Re: Array Deferencing Question
by periapt (Hermit) on Oct 01, 2004 at 19:47 UTC
    Since this is an AoA, $res->[0]->[0] will also work consider
    perl -e"$a=[['ref']];print q|$a\n$a->[0]\n$a->[0]->[0]\n$$a[0]\n$a->[0 +][0]\n$a->[0]->[0]|; " __END__ ARRAY(0x183f0d4) ARRAY(0x183efd8) ref ARRAY(0x183efd8) ref ref

    PJ
    use strict; use warnings; use diagnostics; (if needed)
Re: Array Deferencing Question
by Scarborough (Hermit) on Oct 01, 2004 at 16:14 UTC

    This seems to work for me

    $ar = [1]; print $ar; #prints Array(******) print $$ar[0]; #prints 1

    Or am I just being simple again?

    80% of success is just turning up - Woody Allen