How do I use symbolic references in Perl?

后端 未结 7 1551
栀梦
栀梦 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:49

    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.

提交回复
热议问题