传递哈希和数组的最佳方式是通过引用。引用只是将复杂数据结构作为单个数据点讨论的一种方式——可以存储在标量变量(如$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 的工作原理。
假设您想将三个哈希传递给您的子例程。以下是三个哈希:
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!
}
这可能很好——它允许您修改传递给子例程的数据,或者不好——它允许您无意中修改传递给原始子例程的数据。