perl: ${$i) , python: ?

Richard Jones richardjones at optushome.com.au
Tue Jan 1 18:12:18 EST 2002


On Wed, 2 Jan 2002 09:50, 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"

Is there a reason why you can't put the values in a storage mechanism like a 
dictionary, rather than stuffing them straight into the current variable 
scope?

>>> d = {}
>>> keys = "t1 t2".split()
>>> for key in keys:
...  d[key] = 3
... 
>>> print "%(t1)s %(t2)s"%d
3 3
>>> 


If you _really_ want to do this, and in my opinion it's yecchy, you can. Use 
locals() to ge a handle on the local variables dictionary, and play with 
that...

[... continuing on from before]
>>> d = locals()
>>> for key in keys:
...  d[key] = 3
... 
>>> print t1, t2
3 3
>>> 

Again, I don't recommend this approach because it's ugly, potentially 
dangerous, ...


    Richard




More information about the Python-list mailing list