我正在寻找一个替换的perl程序,但我的循环每次都不起作用。例如,这个概念是:
#!/usr/bin/perl
use warnings;
use strict;
my @array1 = qw(A quick brown fox jumps over the lazy dog);
my @array2 = qw(fox dog);
my @array3 = qw(rabbit cat);
我希望第二个数组与第一个数组进行比较,挑出狐狸和狗的元素,用兔子和猫替换它。
所以这句话应该变成"一只快速的棕色兔子跳过懒猫#34;
这是概念,但数据不同,第二和第三个数组每个可能包含50个元素。任何帮助将不胜感激。
答案 0 :(得分:7)
我做的事情如下:
use strict;
use warnings;
use Data::Dump qw(dump);
my @array1 = qw(A quick brown fox jumps over the lazy dog);
my @array2 = qw(fox dog);
my @array3 = qw(rabbit cat);
my %corresp;
@corresp{@array2} = @array3;
foreach my $word(@array1) {
$word = $corresp{$word} if exists $corresp{$word};
}
dump@array1;
<强>输出:强>
(
"A",
"quick",
"brown",
"rabbit",
"jumps",
"over",
"the",
"lazy",
"cat",
)
答案 1 :(得分:4)
#!/usr/bin/perl
use warnings;
use strict;
my @array1 = qw(A quick brown fox jumps over the lazy dog);
my @array2 = qw(fox dog);
my @array3 = qw(rabbit cat);
my %h;
@h{@array2} = @array3;
@array1 = map { $h{$_} || $_ } @array1;
答案 2 :(得分:0)
我不知道perl,但我认为:(受javascript影响)
function replace (array, oldword, newword){
var i = array.search(oldworld),
a = array.substr(0, i),
n = array.substr(oldword.length, array.length);
return a + newword + b;
}
投入循环应该有效。
(输出示例:)
console.log(replace('A quick brown fox jumps over the lazy dog', 'fox', 'rabbit'));
A quick brown rabbit jumps over the lazy dog
答案 3 :(得分:0)
我自己很新,但这就是我想出来的:
use strict;
use warnings;
my @array1 = qw(A quick brown fox jumps over the lazy dog);
my @array2 = qw(fox dog);
my @array3 = qw(rabbit cat);
my $index = 0;
foreach (@array1) {
$index++ if s/$array2[$index]/$array3[$index]/;
}
print join(' ',@array1), "\n";