简体   繁体   English

在Perl中,应该在传递对哈希/数组的引用和传递hashref / arrayref标量之间进行选择的依据是什么?

[英]In Perl, on what basis should one choose between passing a reference to a hash/array and passing a hashref/arrayref scalar?

To be brief, I'm wondering if there are any best-practice reasons for deciding between: 简而言之,我想知道是否有最佳实践理由来决定:

my %hash = ( foo => 1, bar => 2 );
# some in-between logic
some_func(\%hash);

and

my $hashref = { foo => 1, bar => 2 };
# some in-between logic
some_func($hashref);

Or is purely a style decision? 还是纯粹是风格决定?

These two examples do exactly the same thing. 这两个例子做的完全一样。 So it mainly depends on which is more convenient for what else, if anything, you do with the %list variable and/or $listref variable. 因此,这主要取决于您对%list变量和/或$listref变量是否更方便(如果有)。

Or maybe you'd like to skip the extra variable entirely: 或者,也许您想完全跳过额外的变量:

some_func( { foo => 1, bar => 2 } );

(Less likely now that you've added those "in-between logic" comments.) (现在不太可能添加了“逻辑之间”的注释。)

如上所述,它们是相同的,尽管第一个可以为您在“某些中间逻辑”代码中使用的变量类型(即哈希)提供更好的上下文。

The two are equivalent and interchangeable. 两者是等效的并且可以互换。 The decision should be made based on what is clearest for you. 该决定应基于对您最清楚的决定。

You can also move back and forth: 您也可以来回移动:

my $hashref = {x => 1, y => 2};

our %hash; *hash = $hashref;

some_func($hashref);
some_func(\%hash);    # \%hash == $hashref

In general I prefer to work with the plural forms %name and @name since it results in less line noise due to dereferencing. 通常,我更喜欢使用%name@name的复数形式,因为由于取消引用,它可以减少行噪。 That and some_func(\\%var) is clearer with regard to var 's type than some_func($var) 那和some_func(\\%var)关于var的类型比some_func($var)更清楚

In most cases it won't make a difference, but I have had some nasty bugs that occurred from trying to change where my reference points if I pass in a reference-of list. 在大多数情况下,这没有什么区别,但是如果我通过参考列表,尝试更改参考点会出现一些讨厌的错误。

Unless I really want to change the contents of a pre-existing array or hash, I personally favor using anonymous lists/hashes (like your second example). 除非我真的想更改预先存在的数组或哈希的内容,否则我个人倾向于使用匿名列表/哈希(例如您的第二个示例)。

This is just personal experience, though. 不过,这只是个人经验。 I will admit that maybe if I understood Perl better I would know the objective best practices (if any exist). 我承认,如果我对Perl有更好的了解,我会知道客观的最佳实践(如果有的话)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM