Perl: 配列を扱う

Perl: array.pl

use strict;
use warnings;

# 配列の生成
my @array = ("aaa", "bbb", "ccc");
my @array2 = qw/aaa bbb ccc/;
my @array3 = qw(aaa bbb ccc);
my @array4 = qw[aaa bbb ccc];
my @array5 = qw{aaa bbb ccc};
my @array6 = qw<aaa bbb ccc>;
print("-> @array\n");
print("-> @array2\n");
print("-> @array3\n");
print("-> @array4\n");
print("-> @array5\n");
print("-> @array6\n");

# 一番後ろに要素を追加
my $push = push(@array, "ddd");
print("push: $push\n");
print("-> @array\n");

# 一番後ろを取り出し、カット
my $pop = pop(@array);
print("pop: $pop\n");
print("-> @array\n");

# 一番前に要素を追加
my $unshift = unshift(@array, "000");
print("unshift: $unshift\n");
print("-> @array\n");

# 一番前を取り出し、カット
my $shift = shift(@array);
print("shift: $shift\n");
print("-> @array\n");

# 逆順に並び替える
my @reverse = reverse(@array);
print("reverse: @reverse\n");
print("-> @array\n");

# 並び替える
my @sort = sort(@reverse);
print("reverse_sort: @sort\n");
print("reverse-> @reverse\n");

# 結合
my $join = join("/", @array);
print("join: $join\n");
print("-> @array\n");

# 長さ
my $length = @array;
print("length: $length\n");

# 配列から条件に合う配列の生成 (a または b を含む要素を取り出す)
my @grep = grep(/[ab]/g, @array);
print("grep-> @grep\n");


# 文字列から配列の生成(文字列の分割)
my @split = split(/,/, "0,1,2,3,4");
print("split: @split\n");
my $split_length = @split;
print("split length: $split_length\n");

出力:

-> aaa bbb ccc
-> aaa bbb ccc
-> aaa bbb ccc
-> aaa bbb ccc
-> aaa bbb ccc
-> aaa bbb ccc
push: 4
-> aaa bbb ccc ddd
pop: ddd
-> aaa bbb ccc
unshift: 4
-> 000 aaa bbb ccc
shift: 000
-> aaa bbb ccc
reverse: ccc bbb aaa
-> aaa bbb ccc
reverse_sort: aaa bbb ccc
reverse-> ccc bbb aaa
join: aaa/bbb/ccc
-> aaa bbb ccc
length: 3
grep-> aaa bbb
split: 0 1 2 3 4
split length: 5