[英]Sorting split variables from an array in a Perl script into this specific format?
我写了一个脚本,使用两个参数调用另一个脚本,其中一个是日志文件,另一个是sql文件,我想要捕获的是来自数据库的spid和cid(两个条目),我已经管理过将输出捕获到数组中。 例如325是spid&p58是cid。
325 p58
525 p58
591 p58
1180 p85
但我应该以特定的格式安排它,在那里不能有任何重复的cid,每个cid都应该在它旁边打印spid。 我已经设法拆分阵列,这是我到目前为止所能想到的
p58- 325
p58- 525
p58- 591
p58- 1180
这是所需的格式。
p58-325,525,591,1180
my @results = capture( [0,1,2], $^X, "/asp_batch/bin/clientquery.pl", @ARGV);
my $size = scalar(@results);
for (my $count = 0; $count < $size; $count++)
{
my ($spid, $cid) = split /\s+/, $results[$count];
print $cid, "- ";
print $spid, "\n";
}
使用哈希来收集在cid
上索引的值。 收集完所有内容后,在散列中为每个键输出一行:
my %hash;
for (my $count = 0; $count < $size; $count++)
{
my ($spid, $cid) = split /\s+/, $results[$count];
# the hash value is an anonymous array
# it's created automatically for you when
# you treat the value as a reference
push @{ $hash{$cid} }, $spid;
}
foreach my $cid ( sort keys %hash )
{
say "$cid- ", join " ", @{ $hash{$cid} };
}
这是一种非常常见的Perl技术。 大多数情况下,“只有一次”或“独特”出现在问题中,有人会想要哈希。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.