如何使用变量名引用哈希?

时间:2017-10-21 23:00:49

标签: perl hash hashref

我有一组预定义的哈希表,我想使用变量名称引用其中一个哈希值并访问键值。即使填充了哈希,以下代码也会返回null。我在这里做错了什么,或者有更好的方法来实现这个目标吗?

my %TEXT1 = (1 => 'Hello World',);
my %TEXT2 = (1 => 'Hello Mars',);
my %TEXT3 = (1 => 'Hello Venus',);

my $hash_name = 'TEXT1';

my $hash_ref = \%$hash_name;
print ${$hash_ref}{1};  #prints nothing

3 个答案:

答案 0 :(得分:5)

你所使用的代码很好 *

<!doctype html>
<html>
  <head>
    <title>Socket.IO App</title>
    <style>
     * { 
       margin: 0;
       padding: 0; 
       box-sizing: border-box; 
     }
     body { 
       font: 13px Helvetica, Arial; 
     }
     form { 
       background: #000; 
       padding: 3px; 
       position: fixed;
       bottom: 0; 
       width: 100%; 
     }
     form input { 
       border: 0; 
       padding: 10px; 
       width: 90%; 
       margin-right: .5%; 
     }
     form button { 
       width: 9%; 
       background: rgb(130, 224, 255); 
       border: none; 
       padding: 10px; 
      }
    #messages { 
       list-style-type: none; 
       margin: 0; padding: 0; 
    }
    #messages li { 
       padding: 5px 10px; 
    }
    #messages li:nth-child(odd) { 
       background: #eee; 
    }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
    $(function () {
      var socket = io();
      $('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
      });
    });
    </script>
  </body>
</html>

你做错的主要是http://www.example.com/game,这就是%TEXT = (1 => abc, 42 => def); $name = 'TEXT'; print ref($name); # "" no strict 'refs'; print ${$name}{1}; # "abc" print $name->{42} # "def" $ref = \%$name; print ref($ref); # "HASH" print $ref->{1}; # "abc" print ${$ref}{42}; # "def" 下不允许这种事情的原因。

* - 除非您在use strict 'refs'下运行,否则您应该

答案 1 :(得分:3)

使用哈希来包含哈希值。

my %texts = (
    TEXT1 => { 1 => 'Hello world', },
    TEXT2 => { 1 => 'Hello Mars', },
    TEXT3 => { 1 => 'Hello Venus', },
)

my $hash_name = 'TEXT1';

print $texts{$hash_name}{1}, "\n";

答案 2 :(得分:0)

以下代码是对标量的赋值,而不是散列:

my $hash_name = 'TEXT';

以下代码分配给哈希:

my %hash = ( alpha => 'beta', gamma => 'delta' );

要从哈希中打印单个元素的值,请说:

print $hash{alpha}, "\n";

您可以引用该哈希并将其分配给变量:

my $hashref = \%hash;

从中可以打印出来自hashref的单个元素:

print $hashref->{alpha}, "\n";
相关问题