将 Perl 脚本中数组中的拆分变量排序为这种特定格式?
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
但我应该以特定格式安排它,其中不能有任何重复的 cids,并且每个 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 技术。大多数时候,当 "only once" 或 "unique" 出现在问题中时,有人会伸手去拿散列。
我写了一个脚本,它使用两个参数调用另一个脚本,其中一个是日志文件,另一个是 sql 文件,我试图捕获的是一个 spid 和一个 cid(两个条目),我已经设法将输出捕获到一个数组中。例如 325 是一个 spid & p58 是一个 cid。
325 p58
525 p58
591 p58
1180 p85
但我应该以特定格式安排它,其中不能有任何重复的 cids,并且每个 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 技术。大多数时候,当 "only once" 或 "unique" 出现在问题中时,有人会伸手去拿散列。