如果我使用像这样简单的东西替换另一个字符串
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
错误在哪里?
答案 0 :(得分:2)
你混淆了变量。
试试这个:
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;
答案 1 :(得分:1)
您尝试在替换模式时使用$search
,而不是要替换的实际模式。因此,您尝试将to_be_replaced
替换为XXXXXXXX
。不是174_4492_232313_7078721ec0.jpg
。
您可能想要添加:
$replace_pattern = $correction_hash->{$device}->{$search};
$json =~ s/$replace_pattern/XXXXX/g;