Larsen, Errin M HMMA/IT wrote:
-----Original Message-----
From: Wiggins d'Anconia [mailto:[EMAIL PROTECTED] Sent: Thursday, March 10, 2005 8:55 AM
To: Marcos Rebelo
Cc: Perl Beginners
Subject: Re: Simplify perl -e '$a = [1,2,3,4,7]; print $a->[EMAIL PROTECTED]'



Marcos Rebelo wrote:

This is correctly printing '7' but '$a->[EMAIL PROTECTED]' seems to be encripted code.

Can I write this in a cleaner way?



$a->[-1]; ???


Hi Wiggins,

  for those of us tryin' to keep up at home, can you walk us through
that bit a little?

  Here's what I spot:

  $a = [1,2,3,4,7] # this is initializing a scalar, $a, with a reference
to an array, [1,2,3,4,7]

 # $a-> this is dereferencing the array
 # as I understand it, and I really don't, the $#ARRAYNAME will give you
the number of elements, minus one, of an array?
 #  if that is the case, and then [EMAIL PROTECTED] ALSO derefernces the array, 
so
then
 #  [EMAIL PROTECTED] will be the number of elements in the array referenced by
$a, minus one (or, '4', in this example)


Actually I wasn't quite convinced about the [EMAIL PROTECTED] construct. Because theoretically @$a has already dereferenced the array, but it appears Perl will just do the right thing (amazing how it does that). It could be written as $#{$a} or even!! $#$a, but I am not entirely sure where to hunt in the docs to find that one, probably under the $# construct, but not sure what that is called. possibly in perlvar but I don't have the time to check, and I suspect John Krahn or somebody will chime in with something brilliant :-).


 # so
 print $a->[EMAIL PROTECTED]

 # is equivelant to
 print $a->[4]

 # or, since [EMAIL PROTECTED] will always be the index of the last element of 
the
array:
 print $a->[-1]


Did I get it right? That looks like homework to me ... Why would you ever do that in a practical script?

--Errin


I think you got it. Ever want the last item in a list, I can think of lots of reasons to want that...


http://danconia.org

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to