打印哈希键时Perl奇怪的结果

时间:2015-02-18 08:02:29

标签: perl hash key

my $dat;
$dat{"1","1","1","1","1"}{'CR'} = "2";

foreach my $k1 (keys %dat){
    print $k1;
}

这是我的代码,它应该没有问题,可以在其他计算机上执行,但我的笔记本电脑显示此结果
enter image description here

编译没有错误.....可以告诉我发生了什么?模块不太确定吗?

2 个答案:

答案 0 :(得分:5)

您可以查看perlvar

  

$;   用于多维数组仿真的下标分隔符。如果您将哈希元素称为

$foo{$a,$b,$c}
     

这真的意味着

$foo{join($;, $a, $b, $c)}

默认值为\034,与awk中的SUBSEP相同。如果您的密钥包含二进制数据,则$;可能没有任何安全值。

use strict;
use warnings;

my %dat;
$dat{"1","1","1","1","1"}{'CR'} = "2";
# which is equivalent to
# my $k = join($;, "1","1","1","1","1");
# $dat{$k}{'CR'} = "2";

foreach my $k1 (keys %dat){
    print "$_\n" for map { $_ eq $; ? '$;' : $_ } split //, $k1;
}

输出

1
$;
1
$;
1
$;
1
$;
1

答案 1 :(得分:2)

您的哈希不包含您认为包含的内容。具体来说,它只有一个密钥:

#!/usr/bin/env perl    

use strict;
use warnings;

my %dat;
$dat{"1","1","1","1","1"}{'CR'} = "2";

use Data::Dumper; 
print Dumper \%dat

输出:

$VAR1 = {
          '11111' => {
                           'CR' => '2'
                         }
        };

根据Сухой27的建议,密钥中的1使用$;的值作为分隔符进行连接:

#!/usr/bin/env perl    

use strict;
use warnings;

$; = '---';

my %dat;
$dat{"1","1","1","1","1"}{'CR'} = "2";

use Data::Dumper; 
print Dumper \%dat

输出:

$VAR1 = {
          '1---1---1---1---1' => {
                                   'CR' => '2'
                                 }
        };

$;更改为空字符串,您将获得11111作为输出,我假设您正在期待。