Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: A variable variable.

by quidity (Pilgrim)
on Nov 23, 2000 at 04:23 UTC ( #43060=note: print w/ replies, xml ) Need Help??


in reply to A variable variable.

Actually, that does work:

bash-2.03$ perl -e'$foo = "bar"; $$foo = 1; print "$bar\n"' 1

But like so many things which work, you don't want to do it like that. You are using something called symbolic references, which although allowed by perl are dangerous if you ever let a user get near @array. For instance, they could alter the value of any other variable in your program (like $path_to_utility).

You can do something simillar using hashes:

foreach (@array) { my ($key, $val) = split(/=/, $_); $vars{$key} = $val; }

Or, if you are actually using var1, var2 etc in your program, you might just want to use an array:

foreach (@array) { next unless /var(\d+)=(.*)/; $values[$1] = $2; }


Comment on Re: A variable variable.
Select or Download Code
Re (tilly) 2: A variable variable.
by tilly (Archbishop) on Nov 23, 2000 at 07:01 UTC
    You are missing the point that it is a really, really bad idea to do this for reasons explained by everyone else. Use a hash instead:
    foreach my $var (@array) { my @val = split /=/, $var, 2; $hash{$val[0]} = $val[1]; }
    UPDATE
    I must have accidentally hit the wrong reply. This was meant as a reply to spaz above.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://43060]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (13)
As of 2014-10-01 12:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (18 votes), past polls