Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, access variable by name in an other scalar

Tags:

perl

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

like image 304
chris01 Avatar asked Dec 12 '22 12:12

chris01


2 Answers

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.

like image 79
cjm Avatar answered Dec 15 '22 01:12

cjm


$$varname = 1 does what you want, but this is prohibited when use strict; is in effect, and thus it is considered bad style.

like image 26
jwodder Avatar answered Dec 15 '22 00:12

jwodder