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

Hi

I am struggling to get the element. i want to the get element before the last element stored in array i.e. 'e'.

@arr=('a', 'c', 'd', 'e', 'h');

Thanks

Replies are listed 'Best First'.
Re: Get Element inArray
by gopalr (Priest) on May 25, 2005 at 02:43 UTC
    my $res=$arr[-2]

    UPDATE: changed $ instead of @

      To explain that a little, negative array indices count from the end of the array: -1 is the last element, -2 the one before that, and so on.

      Scalar value @arr[-2] better written as $arr[-2]

      And it should be $arr[-2] (with a $ sigil) at least in current Perl (Perl 6 will change that).

      gopalr said my $res=@arr[-2]

      I think you mean my $res=$arr[-2];
      If you have warnings turned on (which we all should!) it doesn't like the @arr[-2] method. When referring to a scalar element of an array you should specify that it is scalar with $

      -Kevin
      my $a='62696c6c77667269656e6440676d61696c2e636f6d'; while ($a=~m/(^.{2})/s) {print unpack('A',pack('H*',"$1"));$a=~s/^.{2}//s;}