[英]Adding unique elements to a Perl array determined by regex
我正在編寫一個perl腳本來分析錯誤代碼並確定它們是否是唯一的。 該錯誤是唯一的,具體取決於它所在的行。 標准錯誤消息可能是:
RT Warning: No condition matches in 'unique case' statement.
"/user/foo/project", line 218, for ..
很多這些錯誤消息在我正在抓取的字符串中有多個數字。 因此,我想要做的是,在“line”之后抓取第一個出現的數字,並且只有在數組中不存在該值時才將其添加到數組中。 這是我到目前為止所得到的:
my $path = RT Warning: No condition matches in 'unique case' statement.
"/user/foo/project", line 218
$path =~ m/(\d+)/;
print("Error occurs on line $1\n");
if(grep(/^$1$/, @RTarray))
{
print("Not unique.\n");
}
else
{
push(@RTarray, $1);
print("Found a unique error!\n");
}
所以,顯然我沒有檢查它是否在關鍵字“line”之后,因為我不太確定如何根據我當前正在處理正則表達式的方式來做到這一點。 另外,我認為我沒有正確地向我的數組添加元素。 請幫助!
你應該使用哈希。 它具有內置的獨特性,您甚至無需檢查。
這是一個例子:
my %seen;
while (my $line = <$fh>) {
if ($line =~ m/line (\d+)/) {
my $ln = $1;
if ( ! $seen{$ln}++ ) {
# this will check first and then increment. If it was encountered before,
# it will already contain a true value, and thus the block will be skipped.
# if it has not been encountered before, it will go into the block and...
# do various operations on the line number
}
}
}
您現在%seen
包含所有有錯誤的行,以及每行多少行:
print Dumper \%seen:
$VAR1 = {
10 => 1,
255 => 5,
1337 => 1,
}
這告訴我們第10行中有一個錯誤,第1337行中有一個錯誤。根據您的代碼,這些錯誤是唯一的。 第255行中的五個錯誤不是唯一的,因為在日志中出現了五次。
如果你想擺脫它們中的一些,使用delete
刪除整個鍵/值對,或$foo{$1}--
減少或delete $foo{$1} unless --$foo{$1}
減少並在一行中擺脫它。
編輯:我看了你的代碼。 實際上,唯一缺少的是正則表達式和引號。 你真的嘗試過嗎? 有用。 :)
my @RTarray;
while (my $line = <DATA>) {
$line =~ m/line (\d+)/;
print("Error occurs on line $1\n");
if( grep { $_ eq $1 } @RTarray ) { # this eq is the same as your regex, just faster
print("Not unique.\n");
} else {
print "Found a unique error in line $1!\n";
push @RTarray, $1;
}
}
__DATA__
RT Warning: No condition matches in 'unique case' statement. "/user/foo/project", line 218, for
RT Warning: No condition matches in 'unique case' statement. "/user/foo/project", line 3, for
RT Warning: No condition matches in 'unique case' statement. "/user/foo/project", line 44, for
RT Warning: No condition matches in 'unique case' statement. "/user/foo/project", line 218, for
RT Warning: No condition matches in 'unique case' statement. "/user/foo/project", line 7, for
RT Warning: No condition matches in 'unique case' statement. "/user/foo/project", line 7, for
RT Warning: No condition matches in 'unique case' statement. "/user/foo/project", line 7, for
這將打印:
Error occurs on line 218
Found a unique error in line 218!
Error occurs on line 3
Found a unique error in line 3!
Error occurs on line 44
Found a unique error in line 44!
Error occurs on line 218
Not unique.
Error occurs on line 7
Found a unique error in line 7!
Error occurs on line 7
Not unique.
我認為這是正確的。 我有218個雙倍和7個三倍,它發現它們兩個。
我只用一個文件句柄循環替換了缺少引號的字符串,以便在多行上測試它。 我還修復了缺少單詞行的正則表達式,但這個特定錯誤消息甚至不需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.