R.A. Epigonos et al.

[フィルタ] テキストからHTML

秀逸なのはmap{}なんだな。map{}で@Aの全要素に対して置換コマンドを実行しているんだな。map{}は戻り値が配列になるから戻り値を@Aに代入してはいけないんだな。ちなみに戻り値には@Aの各要素に含まれる改行の数が含まれているんだな。

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:\>

ソーシャルブックマーク

  1. はてなブックマーク
  2. Google Bookmarks
  3. del.icio.us

ChangeLog

  1. Posted: 2007-12-07T22:34:33+09:00
  2. Modified: 2007-12-07T04:53:27+09:00
  3. Generated: 2023-08-27T23:09:11+09:00