我有一个字符串,可能包含或不包含某些特定单词。 如果它包含我想要以不同颜色打印字符串的作品之一(取决于单词) 所以我想要一个包含单词列表的数组(例如,一个用于红色字,一个用于黄色,一个用于绿色,如下例所示:
push(@red_word, [ "error","ERROR","Assertion","assertion","Error","ASSERTION","Errors" ]);
push(@yellow_word, [ "WARNING","Warning","warning","PAUSED","Paused","paused","Warnings" ]);
push(@green_word, [ "ACTIVE","Active","active" ]);
$ l是我要检查的字符串,我尝试了类似这样的
foreach my $l (@$lines) {
if ($l =~ @red_word) {
print '<FONT COLOR="FF0000">'.$l.'</FONT><br>';
}
else {
if ($l =~ @yellow_word) {
print '<FONT COLOR="FFFF00">'.$l.'</FONT><br>';
}
else {
if ($l =~ @green_word) {
print '<FONT COLOR="008000">'.$l.'</FONT><br>';
}
else {
print '<FONT COLOR="000000">'.$l.'</FONT><br>';
}
}
}
}
但结果不稳定,有些行以红色打印,与列表red_word没有任何关系。
我做错了什么?
答案 0 :(得分:4)
这不符合您的想法:
push(@red_word, [ "error","ERROR","Assertion","assertion","Error","ASSERTION","Errors" ]);
push(@yellow_word, [ "WARNING","Warning","warning","PAUSED","Paused","paused","Warnings" ]);
push(@green_word, [ "ACTIVE","Active","active" ]);
您正在创建一个二维数据结构的单个元素数组,其中包含一个嵌套数组。
$VAR1 = [
[
'error',
'ERROR',
'Assertion',
'assertion',
'Error',
'ASSERTION',
'Errors'
]
];
因此,这场比赛的效果不会很好。我真的不确定它会做什么,但它不会测试'如果这个词在列表中'。
尝试从数组中构建正则表达式:
my @red_words = (
"error", "ERROR", "Assertion", "assertion",
"Error", "ASSERTION", "Errors"
);
my $is_red = join( "|", map {quotemeta} @red_words );
$is_red = qr/($is_red)/;
print "Red" if $line =~ m/$is_red/;
也许是这样的:
#!/usr/bin/env perl
use strict;
use warnings;
my %colour_map = (
'error' => 'FF0000',
'errors' => 'FF0000',
'assertion' => 'FF0000',
'warning' => 'FFFF00',
'warnings' => 'FFFF00',
'paused' => 'FFFF00',
'active' => '008000',
);
my $search = join( "|", map {quotemeta} keys %colour_map );
$search = qr/\b($search)\b/;
my @lines = (
"line containing assertion",
"a warning",
"green for active",
"A line containing ACTIVE"
);
foreach my $line (@lines) {
if ( my ($word) = $line =~ m/$search/ ) {
print "<FONT COLOR=\"$colour_map{lc($word)}\">$line</FONT><BR/>\n";
}
else {
print "<FONT COLOUR=\"000000\">$line</FONT><BR/>\n";
}
}
(不完全确定是否有办法转换匹配列表。我还有另一种想法)。