【问题标题】:Perl: No replacement of a stringPerl:不替换字符串
【发布时间】:2014-10-06 23:04:00
【问题描述】:

如果我使用类似这样的简单方法替换另一个字符串

my $pet = "I have a dog.";
my $search = "dog";
my $replace = "cat";
$pet =~ s/$search/$replace/;

它工作正常,我得到“我有一只猫。”正如预期的那样。

但是当我使用更复杂的东西时,它不会被替换:

my $image_correction_hash = {};

$device = "my_device";
$correction_hash->{$device}->{'to_be_replaced'} = "174_4492_232313_7078721ec0.jpg";

# my json string
my $json = '[{"credits":[],"issue":174,"layout":"special_cover","text":[],"hide_overline":"","category":"Kunst","id":"174_4492","media_data":[{"thumbnail":"","data_is_cover":1,"subheadline":"","value":"174_4492.jpg","type":"image","headline":""},{"data_position":"left","thumbnail":"","subheadline":"","value":"174_4492_232302_3980b3da34.jpg","data_effect":"smear","type":"image","headline":""},{"data_position":"right","thumbnail":"","subheadline":"","value":"174_4492_232313_7078721ec0.jpg","data_effect":"smear","type":"image","headline":""}],"links":[],"textmarker":"","teaser":"","hide_headline":"","article_thumbnail":"174_4492_article_thumbnail.jpg","subheadline":"","gallery":[],"overline":"","headline":"Covertitel\n"}]';


print STDERR "JSON string before:" . $json . "\n";

foreach my $search ( keys %{$correction_hash->{$device}})
{
    print STDERR "to be replaced:".$correction_hash->{$device}->{$search}.".\n";

    # the replacement
    $json =~ s/$search/XXXXX/g;
}
print STDERR "JSON string after:" . $json . "\n"; # no replacement occured - GRRR

这里的错误在哪里?

【问题讨论】:

    标签: string perl replace


    【解决方案1】:

    你混淆了变量。

    试试这个:

    print STDERR "to be replaced:".$search.".\n";
    

    它会打印这个:to be replaced:to_be_replaced.

    所以你可以使用这个代码:

    my $pattern = $correction_hash->{$device}->{$search};
    $json =~ s/$pattern/XXXXX/g;
    

    附带说明,如果您的 $pattern 不是正则表达式,您应该使用以下代码对其进行转义:

    $json =~ s/\Q$pattern\E/XXXXX/g;
    

    【讨论】:

    • @Thariama 请注意此答案推荐的quotemeta 的可能需求。
    【解决方案2】:

    您尝试在模式替换中使用$search,而不是您要替换的实际模式。所以你试图用XXXXXXXX 替换to_be_replaced。不是174_4492_232313_7078721ec0.jpg

    您可能想要添加:

      $replace_pattern = $correction_hash->{$device}->{$search};
      $json =~ s/$replace_pattern/XXXXX/g;
    

    【讨论】:

    • 第二双眼睛经常会发现你看不到的东西。
    • 绝对正确——而且已经很晚了,所以我不再有完美的智慧了
    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 2013-03-08
    • 2012-09-21
    • 2015-10-11
    • 2014-12-03
    • 2018-06-26
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多