C:\>perl -e "@A=<>; map{s/\n/<br>\n/g}@A; print @A" a.txt
I have a dream that one day this nation <br>
will rise up and live out the true meani<br>
ng of its creed: "We hold these truths t<br>
o be self-evident: all men are created e<br>
qual." on red hills Georgia sons former <br>
slaves slaveowners able sit down togethe<br>
r at table brotherhood. even state Missi<br>
ssippi, desert state, sweltering with he<br>
at injustice oppression, transformed int<br>
o an oasis freedom justice. my four chil<br>
dren in where they not judged by color t<br>
heir skin but content character. today.<br>
C:\>
ちなみにコンパイラは次のように理解しているんだな。
open IN,"$ARGV[0]";
@A=<IN>;
close IN;
map{s/\n/<br>\n/g}@A;
print @A;
こんな風にしても同じ出力なんだな。
C:\>perl -ne "s/\n/<br>\n/g; print;" a.txt
コンパイラ的には次のような感じ。
open IN,"$ARGV[0]";
while(<IN>){
s/\n/<br>\n/g;
print;
}
close IN;
どっちがすっきりしているかってのは微妙なとこなんだな。でも配列の各要素について処理して結果を配列で返すような場合はmap{}を使ったほうがなんとなくお得な感じがするんだな。
話は変わるけど下に様にすると@Aの各要素中に含まれるピリオドの数を出力できるんだな。
C:\>perl -e "@A=<>; @A=map{s/\./<br>\n/g}@A; print map{\"in line \".++$i.\" a \".$_.\" times\n\"}@A;" a.txt
in line 1 a times
in line 2 a times
in line 3 a times
in line 4 a times
in line 5 a 1 times
in line 6 a times
in line 7 a 1 times
in line 8 a times
in line 9 a times
in line 10 a 1 times
in line 11 a times
in line 12 a 2 times
C:\>