我目前正在學習Perl和我試圖找出如何做一個 if string in variable { do stuff
}如何使用if語句確定字符串是否在變量中?
我已經嘗試了許多不同的方法,如使用EQ,和=〜但它返回的所有關鍵字keywords.txt內反對該公司在$行
這裏找到特定的關鍵字是我的腳本:
#!/usr/bin/perl
use strict;
use warnings;
my $keywords = 'keywords.txt';
open(my $kw, '<:encoding(UTF-8)', $keywords)
or die "Could not open file '$keywords' $!"
; # Open the file, throw an exception if the file cannot be opened.
chomp(my @keywordsarray = <$kw>)
; # Remove whitespace, and read it into an array
close($kw); # Close the file
my $syslog = 'syslog';
open(my $sl, '<:encoding(UTF-8)', $syslog)
or die "Could not open file '$keywords' $!"
; # Open the file, throw an exception if the file cannot be opened.
chomp(my @syslogarray = <$sl>); # Remove whitespace, and read it into an array
close($sl); # Close the file
foreach my $line (@syslogarray) {
foreach my $keyword (@keywordsarray) {
if ($keyword =~ $line) {
print "**" . $keyword . "**" . "\n";
}
}
}
是的,這確實工作,謝謝。 – Simon
如果你採用這種方法,你應該考慮提前預編譯你的正則表達式,因爲@ikegami建議低於 –
請注意,這將考慮將行「已放棄」以包含關鍵字「band」。這就是爲什麼我使用'\ b' – ikegami