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

Dear friends,

Now i am studying about array reference

i had doubt in the following line of code

My requirement is, I want to print any 2 element from array using its reference

In my study material i got the answer saying that most of the time don't use @$arr_ref for printing or accessing, use the reference with "->"

@friends=qw(gobi guru muthu kumar sabari naga bal);
$friends_ref=\@friends;
print @$friends_ref[ 2,3 ] # It will print muthu and kumar
print $friends_ref->[ 2,3 ] # it will print only kumar

Why the second line is displaying like this?

Thanks&Regards,
Gobi S.

Replies are listed 'Best First'.
Re: Print element using array reference
by moritz (Cardinal) on Apr 21, 2010 at 12:26 UTC
    Because in Perl the $ means "scalar". A dereferencing expression beginning with a $ can only return one scalar value.
      ok moritz
      can i use print @$friends_ref[ 2,3 ] ;
      is this correct?
Re: Print element using array reference
by arc_of_descent (Hermit) on Apr 21, 2010 at 12:45 UTC

    In the first expression, what you're doing is actually accessing an array slice.

    @friends = qw(gobi guru muthu kumar sabari naga bal); print @friends[ 2, 4 ]; # prints muthu and sabari

    If a list is accessed in scalar context, Perl will return the last element.

      Thanks friends