ハッシュと配列を渡す最良の方法は、参照渡しです。参照とは、複雑なデータ構造を 1 つのデータ ポイント (スカラー変数( など)に格納できるもの) として扱うための単純な方法$foo
です。
参照を読んで、元のデータを取り戻すために参照を作成し、参照を逆参照する方法を理解してください。
非常に基本的なこと: データ構造の前にバックスラッシュを付けて、その構造への参照を取得します。
my $hash_ref = \%hash;
my $array_ref = \@array;
my $scalar_ref = \$scalar; #Legal, but doesn't do much for you...
参照は、元の構造の記憶場所です (および構造に関する手がかり):
print "$hash_ref\n";
次のようなものが出力されます:
HASH(0x7f9b0a843708)
参照を使用可能な形式に戻すには、参照を正しい シジルの前に置くだけです。
my %new_hash = %{ $hash_ref };
これは、Perl で非常に複雑なデータ構造を作成できる方法であり、オブジェクト指向 Perl がどのように機能するかを示すため、参照の使用について学ぶ必要があります。
サブルーチンに 3 つのハッシュを渡したいとしましょう。3 つのハッシュは次のとおりです。
my %hash1 = ( this => 1, that => 2, the => 3, other => 4 );
my %hash2 = ( tom => 10, dick => 20, harry => 30 );
my %hash3 = ( no => 100, man => 200, is => 300, an => 400, island => 500 );
それらの参照を作成します
my $hash_ref1 = \%hash1;
my $hash_ref2 = \%hash2;
my $hash_ref3 = \%hash3;
そして今、参照を渡すだけです:
mysub ( $hash_ref1, $hash_ref2, $hash_ref3 );
参照はスカラーデータであるため、サブルーチンに渡すのに問題はありません。
sub mysub {
my $sub_hash_ref1 = shift;
my $sub_hash_ref2 = shift;
my $sub_hash_ref3 = shift;
今、私はそれらを逆参照するだけで、私のサブルーチンはそれらを使用できます。
my %sub_hash1 = %{ $sub_hash_ref1 };
my %sub_hash2 = %{ $sub_hash_ref2 };
my %sub_hash3 = %{ $sub_hash_ref3 };
refコマンドを使用して、参照が何への参照であるかを確認できます。
my $ref_type = ref $sub_hash_ref; # $ref_type is now equal to "HASH"
これは、正しいタイプのデータ構造が渡されていることを確認したい場合に便利です。
sub mysub {
my $hash_ref = shift;
if ( ref $hash_ref ne "HASH" ) {
croak qq(You need to pass in a hash reference);
}
また、これらはメモリ参照であるため、参照を変更すると元のハッシュが変更されることに注意してください。
my %hash = (this => 1, is => 2, a => 3 test => 4);
print "$hash{test}\n"; # Printing "4" as expected
sub mysub ( \%hash ); # Passing the reference
print "$hash{test}\n"; # This is printing "foo". See subroutine:
sub mysub {
my $hash_ref = shift;
$hash_ref->{test} = "foo"; This is modifying the original hash!
}
これは、サブルーチンに渡されたデータを変更できるという良い場合もあれば、元のサブルーチンに渡されたデータを意図せずに変更できるという場合もあります。