编辑对不起,我忘记了最重要的部分.每个键可以有多个值.向那些已经回答的人道歉.print和join将在以后用于打印多个值$key在一行.
在下面的示例代码中,假设值$keyvalue不断变化,我试图使用单行(或类似包含的内容)来测试并查看当前是否$keyvalue已存在.如果确实如此,则什么也不做.如果没有,那就推吧.这一行将驻留在while语句中,这就是为什么它需要包含在几行内.
只要没有重复值,保留顺序无关紧要.
my $key = "numbers";
my $keyvalue = 1;
my %hash = ($key => '1');
push (@{$hash{$key}}, $keyvalue) unless exists $hash{$key};
Run Code Online (Sandbox Code Playgroud)
我没有收到任何错误use strict; use warnings;,但同时这不起作用.在上面的例子中,我希望的是,由于默认值是1该$keyvalue不会推,因为它是也1.也许我已经让自己全都转过身来......
是否有调整使这个工作或任何替代品可以用来代替完成同样的事情?
最简单的方法是将匿名哈希放在$hash{$key}.你只关心那个匿名哈希的密钥.
#!/usr/bin/perl
use strict; use warnings;
my %hash;
while ( my $line = <DATA> ) {
chomp $line;
my ($key, $val) = split /\s*=\s*/, $line;
$hash{$key}{$val} = undef;
}
for my $key ( keys %hash ) {
printf "%s : [ %s ]\n", $key, join(' ', keys %{ $hash{$key} });
}
__DATA__
key = 1
key = 2
other = 1
other = 2
key = 2
key = 3
Run Code Online (Sandbox Code Playgroud)
在输出中,key = 2只出现一次:
C:\Temp> h other : [ 1 2 ] key : [ 1 3 2 ]