chompとchopと$/
声に出して言うと、チョンプとチョップとダラースラーッシュ!
言ってみたかっただけデス。
chomp
は文字列の最後に改行があれば取り除いてくれて、
chop
は文字列の最後の文字を取り除いて、それを返してくれます。
ちなみに、chomp
の戻り値は、取り除いた文字列の数です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | use v5.10; use strict; use warnings; use Test::More; { is $/, "\n" ; my @got = ( "aaa\n" , "aaa\r" , "aaa\r\n" ); is chomp ( @got ), 2; my @expected = ( "aaa" , "aaa\r" , "aaa\r" ); is_deeply \ @got , \ @expected ; } { local $/ = "\r\n" ; my @got = ( "aaa\n" , "aaa\r" , "aaa\r\n" ); is chomp ( @got ), 2; # length("\r\n") = 2 my @expected = ( "aaa\n" , "aaa\r" , "aaa" ); is_deeply \ @got , \ @expected ; } { local $/ = "\r" ; my @got = ( "aaa\n" , "aaa\r" , "aaa\r\n" ); is chomp ( @got ), 1; my @expected = ( "aaa\n" , "aaa" , "aaa\r\n" ); is_deeply \ @got , \ @expected ; } |
これを実行すると、こんな感じ。
$ perl aaa.pl
ok 1
ok 2
ok 3
ok 4
ok 5
ok 6
ok 7
1..7
chomp
と$/
の関係はこんな感じです。
例えば改行が\rの場合とか、もう大丈夫ですね。
ちなみに、$/
を変更しない場合は、
実行環境によって、$/
が異なるようです。
手元の環境(Mac OS 10.8.5)だと、こんな感じ。
1 2 3 4 5 6 7 | use v5.10; use strict; use warnings; say '$/ is CR' if $/ eq "\r" ; say '$/ is LF' if $/ eq "\n" ; say '$/ is CRLF' if $/ eq "\r\n" ; |
$ perl bbb.pl
$/ is LF
最後に、chop
ですが、リストにも使えるようです。
え?戻り値は???って思った方は、こちらをどうぞ。
1 2 3 4 5 6 7 | use v5.10; use strict; use warnings; my @foo = ( "aaa" , "bbb" , "ccc" ); say chop ( @foo ); say join ( ',' , @foo ); |
最後の要素をchop
したときの結果が格納されるので、
この場合、”ccc”の最後の文字が取得できます。
$ perl ccc.pl
c
aa,bb,cc
ほんのちょっと、賢くなりました。
おしまい。
Leave a Comment