I am pretty sure this works with perl but I dont know how to code it. I can imagine it with eval, but that is not I am looking for.
my $foo = 0;
my $varname = "foo";
$($varname) = 1; # how to do this?
# I want to access a scalar that name is in a other scalar
# so $foo should be 1 now.
Thanks
What you're trying to do is called a symbolic reference, and the syntax is ${$varname}
(or just $$varname
for simple cases). But this is almost always a bad idea, because it tends to produce extremely hard to diagnose bugs. That is why it is prohibited by use strict
.
You can say no strict 'refs'
to allow symbolic references, but you really, really, shouldn't.
The two main alternatives to symbolic references are hashes and hard references. It's hard to say which one is better suited to your situation, because you haven't really explained what you're trying to do.
$$varname = 1
does what you want, but this is prohibited when use strict;
is in effect, and thus it is considered bad style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With