How do I use symbolic references in Perl?

后端 未结 7 1591
栀梦
栀梦 2020-12-02 02:02

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\";         


        
7条回答
  •  天涯浪人
    2020-12-02 02:55

    This is very bad practice. If you ever need to do it, it means you should refactor your code. Perhaps a hash with named keys would be better:

    my %data = (
        'bob' => [ 'jerk', 'perlfan' ],
    );
    my $name = 'bob';
    
    print $data{ $name }->[0], "\n";
    print $data{ $name }->[1], "\n";
    
    my $stringified = join ' and ', @{ $data{ $name } };
    print $stringified, "\n";
    

提交回复
热议问题