[Tutor] Perl equivalent of $#var

Smith, Jeff jsmith at medplus.com
Wed May 18 14:47:32 CEST 2005


The most common usage is to get the last member of an array as with
	myarray[$#myarray]
and I realize in Python, this can be done with
	myarray[-1]

My current dilemma is that I've got a program that takes one argument
and needs to be run multiple times with this argument being validated
based on the previous one.  So proper usage might be
	myprog red
	myprog blue
	myprog green
where it would be wrong to do
	myprog red
	myprog green	
I have a list which gives the proper order
	colors = ['red', 'blue', 'green']

There are places where I need to know specifically if I am on the first
or last sequence of runs so early on I get my current index:
	now = colors.index(sys.argv[1])
and then later I can compare
	if now == 0
or
	if now == len(colors) - 1
which is distinctly ugly and I would prefer
	if now == $#colors

Keep in mind this is not an exact statement of the problem but I believe
it captures the full context.

Jeff

-----Original Message-----
From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu] 
Sent: Tuesday, May 17, 2005 6:00 PM
To: Smith, Jeff
Cc: tutor at python.org
Subject: Re: [Tutor] Perl equivalent of $#var




On Tue, 17 May 2005, Smith, Jeff wrote:

> Is there a more Pythonic way to get the Perl equivalent of
> 	$#var
> other than
> 	len(var) - 1


Hi Jeff,

Just out of curiosity, where do you use Perl's $#var?  Can you show us
the context of its use?  If we see context, it might help us find a
Python idiom that fits the usage.

Best of wishes!



More information about the Tutor mailing list