完成以下最有效的方法是什么? (我知道他们完成同样的事情,但是大多数人如何在三者之间做到这一点,为什么?)
文件a.pl
my %hash = build_hash(); # Do stuff with hash using $hash{$key} sub build_hash { # Build some hash my %hash = (); my @k = qw(hi bi no th xc ul 8e r); for ( @k ) { $hash{$k} = 1; } # Does this return a copy of the hash?? return %hash; }
文件b.pl
my $hashref = build_hash(); # Do stuff with hash using $hashref->{$key} sub build_hash { # Build some hash my %hash = (); my @k = qw(hi bi no th xc ul 8e r); for ( @k ) { $hash{$k} = 1; } # Just return a reference (smaller than making a copy?) return \%hash; }
文件c.pl
my %hash = %{build_hash()}; # Do stuff with hash using $hash{$key} # It is better,because now we don't have to dereference our hashref each time using ->? sub build_hash { # Build some hash my %hash = (); my @k = qw(hi bi no th xc ul 8e r); for ( @k ) { $hash{$k} = 1; } return \%hash; }
解决方法
我更喜欢返回一个哈希参考,有两个原因.一个,它使用了一点点内存,因为没有副本.二,如果你只需要一块哈希就可以这样做.
my $value = build_hash()->{$key};
学习爱哈希引用,一旦你开始使用对象,你将会看到他们很多.