[英]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.