Re: finding the last element in a referenced array

From: Rhesa Rozendaal (perl&nntp_at_rhesa.com)
Date: 10/05/04


Date: Tue, 05 Oct 2004 18:05:42 +0200
To: ".rhavin" <rhavin@shadowtec.de>


.rhavin wrote:
> i want to access the last elemt of an array... sounds like $#array, i
> know, but in my case, the array is stored as a reference in a
> construction like this:
>
> $hash{'%1'}{'%2'}=[1,2,3];
>
> i can access the last element by
>
> $hash{'%1'}{'%2'}[2]
>
> cos i know it is the second, but i need a way to access the last
> element without knowing whether it is the first, or the zeroth or
> whatever.

luckily for you, perl can count backwards too:

        @a = (1,2,3);
        print $a[-1]; # prints 3
        print $a[-2]; # prints 2

> i tried
>
> $hash{'%1'}{'%2'}[$#hash{'%1'}{'%2'}]

Look, the array is dereferenced by

        @{ $hash{'%1'}{'%2'} }

so the last element index would be

        $#{ $hash{'%1'}{'%2'} }

so you'd get at the last element with

        $hash{'%1'}{'%2'}[ $#{ $hash{'%1'}{'%2'} } ];

Of course,

        $hash{'%1'}{'%2'}[ -1 ]

is a bit more readable...

You could also have assigned the reference to a new variable:

        $r = $hash{'%1'}{'%2'};
        $last = $r->[ -1 ];
or
        $last = $r->[ $#$r ];
        

Rhesa



Relevant Pages

  • Re: VB-101: Passing Arrays ByVal vs ByRef
    ... changed if an array is passed by Val. ... ' new reference ... As each function creates a new array object, ... 'secondArray' and 'secondArrayCopy'. ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Need help with textboxes
    ... The JavaScript 1.5 Reference already states: ... All forms and their children are stored in an array ... use dot notation or object literals. ... No. Bracket property accessors allow their argument to be any string value. ...
    (comp.lang.javascript)
  • Re: Garbage Collection Issues in long-standing services
    ... the pinned array should get unpinned or ... The receive case is done quite well, I do create a 4K buffer and reuse it ... and remove the reference to my wrapper socket class, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: How to give selective access to the methods in a class?
    ... different memory locations at different times. ... The reference still leads to the ... So array resizing ... program pushes certain objects into the circular buffer, ...
    (comp.lang.java.programmer)
  • Re: Perlish map() function
    ... the reference material, the Array constructor was introduced in JavaScript ... evaluation would result in a ReferenceError. ... identifier shows that it is true. ...
    (comp.lang.javascript)