In Perl, if a variable holds the name for another variable, how do I use the first variable to visit the other one?
For example, let
$name = \"bob\";
Usually when you think you need to use symbolic references, you will be better served by using a hash (associative array).
use strict;
use warnings;
my %user = (
'bob' => [qw' jerk perlfan '],
'mary' => 'had a little lamb',
);
{
for my $name (qw'bob mary susan'){
if( exists $user{$name} ){
if( ref($user{$name}) eq 'ARRAY' ){
print join( ' ', @{$user{$name}} ), "\n";
}else{
print $name, ' ', $user{$name}, "\n";
}
}else{
print "$name not found\n";
}
}
}
Results in:
jerk perlfan mary had a little lamb susan not found
If you think you really need to use symbolic references, this is a safer way to do that.
use strict;
use warnings;
# can't use my
our @bob = ("jerk", "perlfan");
our $mary = 'had a little lamb';
{
for my $name (qw'bob mary susan'){
if( exists $::{$name} ){
my $ref = $::{$name};
if( *{$ref}{ARRAY} ){
print join(' ',@$ref), "\n";
}elsif( *{$ref}{SCALAR} ){
print "# $name is not an array, it's a scalar\n";
print $name, ' ', $$ref, "\n";
}
}else{
print "$name not found\n"
}
}
}
Which returns:
jerk perlfan # mary is not an array, it's a scalar mary had a little lamb susan not found
You should notice that it is harder to symbolic references safely, which is why you shouldn't use them.
Unless of course you are an expert doing something advanced.