Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

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; }

Replies are listed 'Best First'.
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]; }
    I must have accidentally hit the wrong reply. This was meant as a reply to spaz above.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://43060]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2017-02-21 10:58 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (309 votes). Check out past polls.