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

Hello guys ,, an array with unknow size , how do you get the last value of it.. I am doing this now :
@array = q( hi bye see do ); my $lastword = array[$];
how can I get the last one ,, thanks for help

Edit ar0n -- Changed title from 'array' to 'Getting last value in array'

Replies are listed 'Best First'.
Re: array
by sschneid (Deacon) on Jul 18, 2002 at 19:52 UTC
    @array = q( bonk blip beep bork ); my $last = $array[-1];
    scott.
Re: array
by DamnDirtyApe (Curate) on Jul 18, 2002 at 19:54 UTC

    In Perl, you can use a negative array index to specify how far from the end of the array you are referring to. This will do what you want:

    @array = q( hi bye see do ); my $lastword = $array[-1];

    _______________
    D a m n D i r t y A p e
    Home Node | Email
Re: array
by Nightblade (Beadle) on Jul 18, 2002 at 19:53 UTC
Re: array
by thelenm (Vicar) on Jul 18, 2002 at 20:50 UTC
    Yet another way to do it:
    $last_value = $array[$#array]; # $#array is the last index in @array

    -- Mike

    --
    just,my${.02}

Re: array
by DS (Acolyte) on Jul 18, 2002 at 19:56 UTC
    this should do it as well my $lastvalue = pop(@array);
      Sara/DS/Amoura/whatever, the pop(@array) function is destructive. It will remove the last element from the array (just as shift will remove the first element), it is therefore not a good substitute for $array[-1] under most circumstances. If you don't mind that your array will now be incomplete pop away. :)
      thanks all that was quick :)
Re: Getting last value in array
by screamingeagle (Curate) on Jul 18, 2002 at 23:00 UTC
    here's another way to do it (wouldnt recommend it though :)
    print $array[scalar @array - 1];