【问题标题】:How to replace a variable with another variable in PERL?如何用PERL中的另一个变量替换一个变量?
【发布时间】:2012-10-16 18:59:02
【问题描述】:

我正在尝试替换文本中的所有单词,除了数组中的一些单词。这是我的代码:

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 中的那些。我知道这是正则表达式中使用的变量的问题,但我无法解决问题。

【问题讨论】:

  • 如果您复制 $text 并对其进行替换,则您的脚本可以正常工作。

标签: regex perl search replace match


【解决方案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!

【讨论】:

    【解决方案2】:

    如果不是将表达式应用于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!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-01
      • 2018-09-22
      • 1970-01-01
      • 2022-11-17
      • 2015-10-03
      • 1970-01-01
      • 2016-01-08
      • 2019-09-01
      相关资源
      最近更新 更多