perl: ${$i) , python: ?

Hans Nowak wurmy at earthlink.net
Tue Jan 1 18:09:11 EST 2002


Maxes wrote:
> 
> Hi all.
> 
> How to create variables with dynamic names ?
> simple example on perl:
> #! /usr/bin/perl
> @kl=qw(t1 t2);
> foreach $i (@kl) {
>        ${$i}=3;
> }
> print "$t1 $t2\n";
> 
> #result would be "3 3"

It's questionable whether this is good coding practice, but
the Pythonic equivalent would be something like

>>> kl = ["t1", "t2"]
>>> for i in kl:
	exec "%s = 3" % (i)
>>> print t1, t2
3 3
>>> 

Or you can mess with the locals() or globals() dictionaries,
but this is not guaranteed to work.

--Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==\n') 
       # decode for email address ;-)
Site:: http://www.awaretek.com/nowak/



More information about the Python-list mailing list