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.
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
In general, whenever you think you need symbolic references you should use a hash instead:
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. ;-)