我在同一个哈希的子程序外部和内部创建键。但是,在子例程之后,调用子例程之前创建的键中的值现在被解释为数组引用。哈希键值在perl中的子程序后更改为数组引用
#!/usr/bin/perl
use module;
use strict;
use warnings;
my %hash;
my $count = 0;
my @array = ("a", "b", "c", "d");
for my $letter (@array) {
$hash{$letter} = $count;
$count++;
}
# need "\" to pass in hash otherwise changes
# will get lost outside of subroutine
foreach my $x (sort keys %hash) {
print "first $hash{$x}\n";
}
module::add_ten(\%hash);
foreach my $p (sort keys %hash) {
# $hash{$p} is printing array references, but before it was
# printing the value I desired. What did the subroutine do?
print "second $hash{$p} $hash{$p}->{ten}\n";
}
,这里是与子程序
package module;
sub add_ten {
my $count = 10;
# this passes the full array as reference
my ($hash_ref) = @_; # $hash_ref is actually %hash (yes, the % is not a typo)
my @keys = keys $hash_ref;
foreach my $ltr (sort keys $hash_ref) {
$hash_ref->{$ltr} = { ten => $count };
$count++;
}
}
1;
这里的模块输出:
first 0
first 1
first 2
first 3
second HASH(0x7ff0c3049c50) 10
second HASH(0x7ff0c3049bc0) 11
second HASH(0x7ff0c3049b90) 12
second HASH(0x7ff0c3049b60) 13
我期待的输出为:
first 0
first 1
first 2
first 3
second 0 10
second 1 11
second 2 12
second 3 13
我修改了我的模块:
package module;
sub add_ten {
my $count = 10;
# this passes the full array as reference
my ($hash_ref) = @_; # $hash_ref is actually %hash (yes, the % is not a typo)
my @keys = keys $hash_ref;
foreach my $ltr (sort keys $hash_ref) {
$hash_ref->{$ltr}{ten}=$count;
$count++;
}
}
1;
和主脚本(注释掉使用严格,以得到它的工作需要):
#!/usr/bin/perl
use module;
#use strict;
use warnings;
my %hash;
my $count = 0;
my @array = ("a", "b", "c", "d");
for my $letter (@array) {
$hash{$letter} = $count;
$count++;
}
# need "\" to pass in hash otherwise changes
# will get lost outside of subroutine
foreach my $x (sort keys %hash) {
print "first $hash{$x}\n";
}
module::add_ten(\%hash);
foreach my $p (sort keys %hash) {
print "second $hash{$p} $hash{$p}{ten}\n";
}
,但是这是我试图去。
这番话应该读'%$ hash_ref是%hash' – ikegami
'使用module'应该是'使用Module',模块本身应该是'Module.pm'和遏制一个package语句'package Module' – Borodin