String(文字列処理)





文字の削除


SYNTAX chop string chomp LIST RET 削除された末尾の1文字 DESC 対象の文字列の末尾の文字を削除する。 POINT Perl ではファイルから読まれた行は最後の改行は含まれる chomp は改行があれば, 削除して、( なければ何もしない )
my $s = "abc" my $ret = chop( $s ); # "c" print ( $ret ); # "ab" print ( $s );
WARNING 引数となる文字列に削除をするため定数は指定できない
# BAD chop( "abc" ); # OK my $s = "abc"; chop( $s );



Substitute


SYNTAX s/ptn/regexp/ DESC 置換演算子
{ $word = "foo"; $word =~ s/foo/bar/; # bar print $word; }
# 繰り返すには /g. 途中の文字でも Matching する { my $var="jinmin no jinmin ni yoru jinmin no tameno Seiji"; $var=~s/jinmin/ore/g; # RET: ore no ore ni yoru ore no tameno Seiji print $var; } { my $var = "ore ore ore ore"; # 行頭だけ Match したい場合は "^" $var =~ s/^ore/foo/g; # RET: foo ore ore ore print $var; }


検索


SYNTAX m/pattern/ DESC pattern を検索する
# Grep と同じ操作 while (<stdin>) { if ( m/test/ ) { print; } }
if( "Wikibooks" =~ /book/){ print "Match!"; }else{ print "Not match."; }



結合(strcat)


my $str = "aaa" . "bbb";



substr


DESC 部分文字列をかえす SYNTAX $ret = length( $str ); SYNTAX $ret = substr( $str, offset [,length [, replace ] ] );
# 4 番目から最後まで # efgh substr("abcedefgh", 4 ); # - を指定すると 最後から N 番目の位置になる # 後ろから 1 番目から最後まで # c substr( "abc", -1 ); # 0 番目から 2 個 # ab substr( "abc", 0, 2 ); # - を指定すると 後ろから 2 番目の位置の文字まで # a substr( "abc", 0, -2 ); # ef substr( "abcedefgh", 4, -2 ) -> ef // 前後から指定 # 4 番目から最後まで



index


DESC regexp に一致する index をかえす RET N >= 0 : match した index -1 : match しない
# -1 index("aiueo", "foobar"); # 2 index("aiueo", "ueo");



length


DESC 文字列の byte 数をかえす
# 3 length( "abc" ) # 6 # ( SJIS ) print length( "あいう" ); # 9 # ( utf-8 ) print length( "日本語" );



substitute


SYNTAX s/regexp/置換文字列/
$s = "This is a pen."; # this is a book $s =~ s/pen/book/; # 空白文字削除. $s =~ s/\s//g;