[英]Search and replace in Perl
I want to search a sentence and replace it with the value of hash that matched string like this: 我想搜索一个句子并将其替换为匹配字符串的哈希值,如下所示:
my $sentence = "abc def hello hi";
$sentence =~ s/abc def/$hash{'abc def'}/g;
I am not getting the correct output. 我没有得到正确的输出。 Can any one please help me? 谁能帮帮我吗?
This works for me: 这对我有用:
#!/usr/bin/env perl
use strict;
use warnings;
my %hash = ( 'abc def' => 'pqr xyz' );
my $sentence = "abc def hello hi";
$sentence =~ s/abc def/$hash{'abc def'}/g;
print "$sentence\n";
When run, it prints: 运行时,它会打印:
pqr xyz hello hi
If that's not what you expected, what were you expecting? 如果这不是你的预期,那你还期待什么? (Note that there were a number of typos in the original version of the Perl code in the question; I assumed they were incidental, but maybe they were key to your problem. Using use strict;
and use warnings;
helps spot problems such as misspelled variable names.) (请注意,在问题的原始版本的Perl代码中存在一些拼写错误;我认为它们是偶然的,但也许它们是您的问题的关键。使用use strict;
并use warnings;
帮助发现拼写错误的问题变量名。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.