为什么要在Perl中返回散列或散列引用?

前端之家收集整理的这篇文章主要介绍了为什么要在Perl中返回散列或散列引用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
完成以下最有效的方法是什么? (我知道他们完成同样的事情,但是大多数人如何在三者之间做到这一点,为什么?)

文件a.pl

  1. my %hash = build_hash();
  2. # Do stuff with hash using $hash{$key}
  3. sub build_hash
  4. {
  5. # Build some hash
  6. my %hash = ();
  7. my @k = qw(hi bi no th xc ul 8e r);
  8. for ( @k )
  9. {
  10. $hash{$k} = 1;
  11. }
  12.  
  13. # Does this return a copy of the hash??
  14. return %hash;
  15. }

文件b.pl

  1. my $hashref = build_hash();
  2. # Do stuff with hash using $hashref->{$key}
  3. sub build_hash
  4. {
  5. # Build some hash
  6. my %hash = ();
  7. my @k = qw(hi bi no th xc ul 8e r);
  8. for ( @k )
  9. {
  10. $hash{$k} = 1;
  11. }
  12.  
  13. # Just return a reference (smaller than making a copy?)
  14. return \%hash;
  15. }

文件c.pl

  1. my %hash = %{build_hash()};
  2. # Do stuff with hash using $hash{$key}
  3. # It is better,because now we don't have to dereference our hashref each time using ->?
  4.  
  5. sub build_hash
  6. {
  7. # Build some hash
  8. my %hash = ();
  9. my @k = qw(hi bi no th xc ul 8e r);
  10. for ( @k )
  11. {
  12. $hash{$k} = 1;
  13. }
  14.  
  15. return \%hash;
  16. }

解决方法

我更喜欢返回一个哈希参考,有两个原因.一个,它使用了一点点内存,因为没有副本.二,如果你只需要一块哈希就可以这样做.
  1. my $value = build_hash()->{$key};

学习爱哈希引用,一旦你开始使用对象,你将会看到他们很多.

猜你在找的Perl相关文章