In PHP, I can write:
$vname = \'phone\';
$$vname = \'555-1234\';
print $phone;
... And the script will output \"555-1234\".
Is ther
You can't do this with the strict pragma enabled, and the strict pragma should usually always be enabled. You can do it with the pragma off though, take a look at this one liner:
perl -le 'my $vname = "phone"; ${ $vname } = "555-1234"; print $phone'
That will work, but this will not:
perl -Mstrict -le 'my $vname = "phone"; ${ $vname } = "555-1234"; print $phone'
"-Mstrict" tells it to "use strict".
It is almost always better to use a hash for something like this, which is about the same as an associative array in PHP.
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.)
You can do it in a very similar way:
$vname = "phone";
$$vname = "555-1234";
print $phone;
But that you can doesn't mean that you should. The best way to manage this is, as Michael Carman says, USE A HASH!
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. ;-)
You do realize that PHP inherits many of its features from Perl, right?
Not only can Perl do all of the symbolic reference stuff PHP can,
use strict;
use warnings;
use 5.010;
our $test=1;
# Access $test through the special hash %::
say ${$::{test}}++;
# This is essentially what the previous line did.
say ${\$test}++
# Same as $test
say ${test}++;
{
# PHP's simple symbolic ref
my $ref = "test";
no strict 'refs';
say $$ref++;
say ${"test"}++;
}
{
package d;
say ${$main::{test}}++;
my $ref = $main::{"test"};
say $$ref++;
$ref = \$main::test;
say $$ref++;
}