Re: finding the last element in a referenced array
From: Rhesa Rozendaal (perl&nntp_at_rhesa.com)
Date: 10/05/04
- Next message: Diane: "How do I print from the cgi to which I am posting using post_https?"
- Previous message: Tore Aursand: "Re: finding the last element in a referenced array"
- In reply to: .rhavin: "finding the last element in a referenced array"
- Next in thread: .rhavin: "Re: finding the last element in a referenced array"
- Reply: .rhavin: "Re: finding the last element in a referenced array"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: Diane: "How do I print from the cgi to which I am posting using post_https?"
- Previous message: Tore Aursand: "Re: finding the last element in a referenced array"
- In reply to: .rhavin: "finding the last element in a referenced array"
- Next in thread: .rhavin: "Re: finding the last element in a referenced array"
- Reply: .rhavin: "Re: finding the last element in a referenced array"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|