それを小さなプログラムに入れると、このようなことができます。上部のコメントアウトされた部分は、複数の行のペアで機能することを示しています。ただし、私が作成した方法では、テキスト ファイルをパイプする必要があります。
# my $text = qq~Letter A = "AAA"
# Letter B = "BBB"
# Letter C = "CCC"
# Letter D = "DDD"~;
#
# my @temp = split /\n/, $text;
my @temp = <>;
for (my $i=0; $i <= $#temp; $i+=2) {
$temp[$i] =~ m/"(\w+)"/;
my $w1 = $1;
$temp[$i+1] =~ s/"(\w+)"/"$w1"/;
my $w2 = $1;
$temp[$i] =~ s/"$w1"/"$w2"/;
}
print join "\n", @temp;
出力:
Letter A = "BBB"
Letter B = "AAA"
Letter C = "DDD"
Letter D = "CCC"
間に他の行がある場合、コードは次のようになります。
my $text = qq~Letter A = "AAA"
testtesttest
Letter B = "BBB"
loads
of text
Letter C = "CCC"
Letter D = "DDD"
Letter E = "EEE"
Letter F = "FFF"~;
my @temp = split /\n/, $text;
# my @temp = <>;
my $last_index; # use this to remember where the last 'fist line' was
for (my $i=0; $i <= $#temp; $i+=1) {
if (!defined $last_index) {
# if we have not find a 'first line' yet, look if this is it
$last_index = $i if $temp[$i] =~ m/"(\w+)"/;
} elsif ($temp[$i] =~ m/"(\w+)"/) {
# otherwhise if we already have a 'first line', check if this is a 'second line'
$temp[$last_index] =~ m/"(\w+)"/; # use the 'first line'
my $w1 = $1;
$temp[$i] =~ s/"(\w+)"/"$w1"/; # and the current line
my $w2 = $1;
$temp[$last_index] =~ s/"$w1"/"$w2"/;
$last_index = undef; # remember to reset the 'first line'
}
}
print join "\n", @temp;
出力:
Letter A = "BBB"
testtesttest
Letter B = "AAA"
loads
of text
Letter C = "DDD"
Letter D = "CCC"
Letter E = "FFF"
Letter F = "EEE"