我在哈希散列中访问变量时遇到问题我不知道我做错了什么。调试hash%list1的值会给出一个undef,所以我无法得到我的值。
use strict ;
use warnings ;
my $text = "The, big, fat, little, bastards";
my $Author = "Alex , Shuman ,Directory";
my %hashes = {1,2,3,40};
my %count = ();
my @lst = split(",",$text);
my $i = 0 ;
my @Authors = split(",", $Author);
foreach my $SingleAuthor(@Authors)
{
foreach my $dig (@lst)
{
$count{$SingleAuthor}{$dig}++;
}
}
counter(\%count);
sub counter
{
my $ref = shift;
my @SingleAuthors = keys %$ref;
my %list1;
foreach my $SingleAuthor1(@SingleAuthors)
{
%list1 = $ref->{$SingleAuthor1};
foreach my $dig1 (keys %list1)
{
print $ref->{$SingleAuthor1}->{$dig1};
}
}
}
答案 0 :(得分:5)
在两个地方,您尝试为哈希分配哈希引用,这会产生此警告:引用找到偶数大小的列表。
以下是您需要的两个修改:
# I changed {} to ().
# However, you never use %hashes, so I'm not sure why it's here at all.
my %hashes = (1,2,3,40);
# I added %{} around the right-hand side.
%list1 = %{$ref->{$SingleAuthor1}};
有关复杂数据结构的有用且简短的讨论,请参阅perlreftut。
对于它的价值,可以通过删除中间变量来简化counter()
方法而不会损失可读性。
sub counter {
my $tallies = shift;
foreach my $author (keys %$tallies) {
foreach my $dig (keys %{$tallies->{$author}}) {
print $tallies->{$author}{$dig}, "\n";
}
}
}
或者,正如ysth指出的那样,如果你不需要钥匙就这样:
foreach my $author_digs (values %$tallies) {
print $dig, "\n" for values %$author_digs;
}
答案 1 :(得分:4)
当我运行你的代码时,Perl告诉我究竟是什么问题。
$ ./hash
Reference found where even-sized list expected at ./hash line 7.
Reference found where even-sized list expected at ./hash line 30.
Use of uninitialized value in print at ./hash line 34.
Reference found where even-sized list expected at ./hash line 30.
Use of uninitialized value in print at ./hash line 34.
Reference found where even-sized list expected at ./hash line 30.
Use of uninitialized value in print at ./hash line 34.
如果不清楚,您可以打开诊断程序以获取更详细的说明。
$ perl -Mdiagnostics hash
Reference found where even-sized list expected at hash line 7 (#1)
(W misc) You gave a single reference where Perl was expecting a list
with an even number of elements (for assignment to a hash). This usually
means that you used the anon hash constructor when you meant to use
parens. In any case, a hash requires key/value pairs.
%hash = { one => 1, two => 2, }; # WRONG
%hash = [ qw/ an anon array / ]; # WRONG
%hash = ( one => 1, two => 2, ); # right
%hash = qw( one 1 two 2 ); # also fine