在我的 Perl 代码中,我最终得到了如下所示的哈希引用。我想从中访问单个元素。我尝试了多种方法,但我无法获取它。
#!/usr/bin/perl
#use strict;
use Data::Dumper;
my %h={'one'=>1,'two'=>2};
print Dumper($h{'one'});
输出
$VAR1 = undef;
使用括号来构造您的哈希,而不是大括号:
use strict;
use warnings;
use Data::Dumper;
my %h = ('one'=>1, 'two'=>2);
print Dumper($h{'one'});
大括号用于构造散列引用。
另外, add use warnings;
,它会生成一条消息,表明您的代码存在问题。
或者,如果你真的想要一个 hashref:
my $h = {'one'=>1, 'two'=>2};
print "$h->{one}\n";
What you've (accidentally) done there, is to create a hash with a key that is a stringified hash reference and a value that is undef
. And perldoc perlref
has a section called WARNING: Don't use references as hash keys.