下面的脚本将为每个键打印每个元素的所有标量值,以及如何仅打印哈希中每个元素的第一个标量值。
#!/usr/bin/perl
use warnings;
use strict;
use Tie::IxHash;
my %KEY_VALUE;
tie %KEY_VALUE,'Tie::IxHash';
my %KEY_VALUE= (
0 => ['A','A','C','B','D'],
1 => ['C','C','C','F','E','E'],
2 => ['Z','X','X','A','A','Y','Y'],
3 => ['A','A','B','B'],
4 => ['E','E','R','M','M'],
5 => ['D','F','F','F','E','E'],
);
while (my ($k, $v) = each %KEY_VALUE)
{
print "KEY= $k ";
print scalar "VALUE= @$v\n"; #But this will print all the value
}
想要的输出:
KEY= 0 VALUE:0 2 3 4 #The scalar value of first A C B D, start with 0
KEY= 1 VALUE:0 3 4 #The scalar value of first C F E
KEY= 2 VALUE:0 1 3 5 #The scalar value of first Z X A Y
KEY= 3 VALUE:0 2 #The scalar value of first A B
KEY= 4 VALUE:0 2 3 #The scalar value of first E R M
KEY= 5 VALUE:0 1 4 #The scalar value of first D F E
答案 0 :(得分:4)
my @vals = qw( Z X X A A Y Y );
my %seen;
my @positions = grep { !$seen{ $vals[$_] }++ } 0..$#vals;
即使未对相同的字符串进行分组,此解决方案仍然有效。
答案 1 :(得分:2)
替换
print scalar "VALUE= @$v\n"; #But this will print all the value
使用
say "VALUE:0 ", join ' ', grep $v->[$_] ne $v->[$_ - 1], 1 .. $#$v;
仅当同一字母从未出现在其首次出现的组之外时(例如,A A B B A
不会发生),该选项才有效。如果可能发生这种情况,请参阅ikegami的答案(带有哈希值)以跟踪已报告的字母。