我正在尝试替换文本中的所有单词,除了我在数组中的一些单词。这是我的代码:
my $text = "This is a text!And that's some-more text,text!";
while ($text =~ m/([\w']+)/g) {
next if $1 ~~ @ignore_words;
my $search = $1;
my $replace = uc $search;
$text =~ s/$search/$replace/e;
}
但是,该程序不起作用。基本上我试图使所有单词大写但跳过@ignore_words中的单词。我知道正则表达式中使用的变量存在问题,但我无法解决问题。
答案 0 :(得分:1)
#!/usr/bin/perl
my $text = "This is a text!And that's some-more text,text!";
my @ignorearr=qw(is some);
my %h1=map{$_ => 1}@ignorearr;
$text=~s/([\w']+)/($h1{$1})?$1:uc($1)/ge;
print $text;
运行时,
THIS is A TEXT!AND THAT'S some-MORE TEXT,TEXT!
答案 1 :(得分:0)
如果不是将表达式应用于while
循环的同一控制变量,您可以从代码中找出问题,只需让s/../../eg
为您全局执行:
my $text = "This is a text!And that's some-more text,text!";
my @ignore_words = qw{ is more };
$text =~ s/([\w']+)/$1 ~~ @ignore_words ? $1 : uc($1)/eg;
print $text;
跑步时:
THIS is A TEXT!AND THAT'S SOME-more TEXT,TEXT!