刚从 Python 接触到 Perl 世界,想知道是否有一种简单的方法可以将翻译 或替换 限制为短语中的一个单词?
在示例中,第二个单词 kind 也更改为 lind。有没有一种简单的方法来进行翻译而无需深入研究一些循环?谢谢。
第一个词已正确翻译为gazelle,但如您所见,第二个词也已更改。
my $string = 'gazekke is one kind of antelope';
my $count = ($string =~ tr/k/l/);
print "There are $count changes \n";
print $string; # gazelle is one lind of antelope <-- kind becomes lind too!
最佳答案
我不知道 tr
在第一个单词后停止翻译的选项。
但是您可以为此使用带反向引用的正则表达式。
use strict;
my $string = 'gazekke is one kind of antelope';
# Match first word in $1 and rest of sentence in $2.
$string =~ m/(\w+)(.*)/;
# Translate all k's to l's in the first word.
(my $translated = $1) =~ tr/k/l/;
# Concatenate the translated first word with the rest
$string = "$translated$2";
print $string;
输出:瞪羚是一种羚羊
关于regex - 将翻译限制在短语中的一个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73353559/