Does Perl have PHP-like dynamic variables?


Question

In PHP, I can write:

$vname = 'phone';
$$vname = '555-1234';
print $phone;

... And the script will output "555-1234".

Is there any equivalent in Perl?

Is there any way to constrain $phone to the scope of the local block, as if I'd written my $phone? Using my $$vname gives me "Can't declare scalar dereference in my at ..." errors.

1
11
4/9/2016 7:22:19 PM

Accepted Answer

What you're attempting to do is called a "symbolic reference." While you can do this in Perl you shouldn't. Symbolic references only work with global variables -- not lexical (my) ones. There is no way to restrict their scope. Symbolic references are dangerous. For that reason they don't work under the strict pragma.

In general, whenever you think you need symbolic references you should use a hash instead:

my %hash;
$hash{phone} = '555-1234';
print $hash{phone};

There are a few cases where symrefs are useful and even necessary. For example, Perl's export mechanism uses them. These are advanced topics. By the time you're ready for them you won't need to ask how. ;-)

56
11/12/2008 2:25:22 AM

Read Mark-Jason Dominus's rants against doing this in Why it's stupid to `use a variable as a variable name'.

You would limit the scope of your changes to $phone by starting the block with

local $phone;

or even

local $$vname;

(Though either changes $phone for any subs called from your block too, so it's not the same as the lexical scope of a my() declaration.)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon