cLive ;-) has asked for the wisdom of the Perl Monks concerning the following question:

Something seems counterintuitive about using $# with array refs:

my @array = (1,2,3,4,5,6,7); print "scalar co print "array last index - $#array\n"; my $arrayref = [1,2,3,4,5,6]; print "arrayref last index - $#$arrayref\n";

Why does this work? The syntax looks wrong to me?

cLive ;-)

update - looking at the array in scalar context makes it easier to see, but it still feels weird to me:

print "array scalar context - ".@array."\n"; print "arrayref scalar context - ".@$arrayref."\n";

Replies are listed 'Best First'.
Re: last index of array ref...
by borisz (Canon) on Apr 02, 2005 at 00:02 UTC
    Maybe you find it easier with braces.
    $aref = [qw/1 2 3/]; print $#$aref; print $#{$aref}; # it is not the same as scalar(@$aref) print scalar(@$aref);
    Boris
Re: last index of array ref... (4 rules)
by tye (Sage) on Apr 02, 2005 at 03:37 UTC

    References quick reference breaks dereferencing down into the 4 simple rules, which makes it easier to remember and less confusing. You case is covered by the first two rules.

    - tye        

Re: last index of array ref...
by Roy Johnson (Monsignor) on Apr 01, 2005 at 23:55 UTC
    $# works pretty much the same way @ does. You can stick either of them on a scalar variable hashref or on an array name.

    Caution: Contents may have been coded under pressure.
Re: last index of array ref...
by ikegami (Patriarch) on Apr 02, 2005 at 00:29 UTC
    @array vs @{$arrayref} $array[0] vs ${$arrayref}[0] $#array vs $#{$arrayref}

    It's definitely consistent. I don't see the problem.

Re: last index of array ref...
by brian_d_foy (Abbot) on Apr 02, 2005 at 02:31 UTC

    If the reference is in a simple scalar (so not a single element access to a hash, function return value, or something else), you can replace the name portion of the variable with the reference.

    Sometimes it looks weird, but I tell people to take a deep breath, then start from the inside. Isolate the reference, then find the other parts that gives away the variable type (like @, $#, or [] for arrays, % or {} for hashes, and so on).

    With practice, it gets better. :)

    --
    brian d foy <brian@stonehenge.com>
Re: last index of array ref...
by ysth (Canon) on Apr 02, 2005 at 01:17 UTC
    That's the cardinal rule of references; wherever you'd have an array name (sans sigil), you can have $simple_scalar_holding_arrayref or {expression yielding arrayref}.
Re: last index of array ref...
by Anonymous Monk on Apr 02, 2005 at 06:47 UTC
    Something seems counterintuitive -- Why? It works the same as with arrays.