2024/02/13 22:13:39

Perl のリファレンス

これを超えれば世界が変わる

リファレンスは、Perlで複雑な構造体を扱うために欠かせません。
最初は難しく思えるかもしれませんが、慣れればなんてことはありません。

リファレンスの中身をのぞく

リファレンスの中身をのぞきたい場合は、Data::Dumper が便利です。

use Data::Dumper;

my $env_ref = \%ENV;

die Dumper $env_ref;

それぞれのリファレンス

スカラー

# スカラーのリファレンス
my $scalar = 'foo';
my $ref_scalar = \$scalar;

# スカラーの無名リファレンス
my $anony_ref_scalar = \"foo"; # can not change
my $anony_ref_scalar2 = \do{"foo"};

リスト

# リストのリファレンス
# () の中に要素を並べます
my @list = (1, 2, 3);
my $ref_list = \@list;

# リストの無名リファレンス
# [] の中に要素を並べます
my $anony_ref_list = [1, 2, 3];

ハッシュ

# ハッシュのリファレンス
# () の中にキーと値を並べます
my %hash = (
    color => 'red',
    code  => 'FF0000',
);
my $ref_hash = \%hash;

# ハッシュの無名リファレンス
# {} の中にキーと値を並べます
my $anony_ref_hash = {
    color => 'red',
    code  => 'FF0000',
};

# ちょっと複雑な例
my $ref = {
    foo => [
        { color => 'red',  code => 'FF0000', },
        { color => 'blue', code => '0000FF', },
    ],
    bar => [
        { color => 'green', code => '00FF00', },
    ],
};

コードリファレンス

リファレンスは変数だけでなく、サブルーチンもあります。

my $ref_code = sub {
    print $_[0] ** 2;
};
$ref_code->('hoge');
サイト内検索