配列に関する関数のまとめ
chop, chomp
スカラと一緒。
各要素に対して、chop、chompを行う。
grep
コマンドのgrepと機能は一緒。
返り値は配列になるので、@hogeで受け取る必要あり。
@list = qw/abc def ghi jkl mno/;
@greped = grep(/^a/i, @list); # grep started with a
$size = grep(/^a/i, @list); # get size started with a
join
配列をデリミタを使用して文字列へ。
@list = qw/abc def ghi jkl mno/;
print join("\t", @list);
# print abc <tab> def <tab> ghi <tab> jkl <tab> mno
pop
配列の最後のindexを取り出す。配列からは削除する。
@list = qw/abc def ghi jkl mno/;
print pop(@list); # print mno
print $#list; # print 3
push
配列の最後に値を足す。
@list = qw/abc def ghi jkl mno/;
push(@list, "pqr", "stu", "vwx");
print @list; # print abc def ghi jkl mno pqr stu vwx
shift
配列の頭を削除して、1個ずつつめる。返り値はさっきまで頭に入っていた値。
引数がなかった場合は、コマンド実行引数、またはサブルーチンの引数がshiftされる。
@list = qw/abc def ghi jkl mno/;
$shifted = shift(@list);
print $shifted; # print abc
print @list; # print def ghi jkl mno
unshift
先頭に値を代入して、既存の要素を後ろへずらす。
@list = qw/abc def ghi jkl mno/;
unshift(@list, "zzz");
print @list; # print zzz abc def ghi jkl mno
splice
配列から値を抽出、そして置換を同時に行う。
OFFSETと、LENGTH(任意)が指定可能。
@list = qw/abc def ghi jkl mno/;
@spliced = splice(@list, 1, 3, "pqr stu");
print @spliced; # print abc pqr stu mno
print @list; # print def ghi jkl
split
文字列をデリミタで分割して配列を返す。
デリミタは文字での指定と、正規表現での指定が可能。
これらの動き方は違う。
$target = " abc def ghi jlk ";
@list1 = split(" ", $target);
@list2 = split(/ /, $target);
@list3 = split(/ /, $target, -1);
print "list1:\t", join(",", @list1), "\n";
print "list2:\t", join(",", @list2), "\n";
print "list3:\t", join(",", @list3 ), "\n";
#### output
$ perl sample.pl
list1: abc,def,ghi,jlk
list2: ,,abc,def,,ghi,jlk
list3: ,,abc,def,,ghi,jlk,,
sort
指定した配列をソートして返す。
ソート用関数を引数で渡すことも可能。
@list = qw/a d c f b/;
print sort(@list); # print a b c f
関数を渡す例
@list = (-10, 2, 3, 1)
sub numeric { $a <=> $b;}
print sort numeric @list; # print -10 1 2 3
reverse
指定した配列の順番を逆にして返す。
@list = qw/a b c/;
print reverse @list; # print c b a
最終更新:2011年07月17日 21:04