从函数返回哈希的最佳Perl练习是什么? [英] What's the best Perl practice for returning hashes from functions?
问题描述
我正在研究传递函数返回数据的散列引用的最佳做法。
一方面,仅将输入值传递给函数并且只返回输出变量似乎很直观。但是,在Perl中传递哈希只能通过引用完成,所以它有点混乱,看起来更像是一个犯错的机会。
另一种方法是在输入变量中传递一个引用,但是它必须在函数中处理,并且可能不清楚输入是什么什么是返回变量。
对此的最佳实践是什么?
返回对数组和散列的引用,然后解引用<$ p
$ b
($ ref_array,$ ref_hash)= $ this-> getData('input');
@array = @ {$ ref_array};
%hash =%{$ ref_hash};
将引用(@array,%hash)传递给将保存输出数据的函数。 / p>
$ this-> getData('input',\ @ array,\%hash);
只需返回参考。无需像您在示例中那样对整个
散列进行解引用。
my $ result = some_function_that_returns_a_hashref ;
表示Foo is,$ result-> {foo};对于键%$ result,
表示$ _,=>,$ result-> {$ _};
等。
我从未见过任何人通过空引用来保存结果。这是Perl,而不是C。
I am mulling over a best practice for passing hash references for return data to/from functions.
On the one hand, it seems intuitive to pass only input values to a function and have only return output variables. However, passing hashes in Perl can only be done by reference, so it is a bit messy and would seem more of an opportunity to make a mistake.
The other way is to pass a reference in the input variables, but then it has to be dealt with in the function, and it may not be clear what is an input and what is a return variable.
What is a best practice regarding this?
Return references to an array and a hash, and then dereference it.
($ref_array,$ref_hash) = $this->getData('input');
@array = @{$ref_array};
%hash = %{$ref_hash};
Pass in references (@array, %hash) to the function that will hold the output data.
$this->getData('input', \@array, \%hash);
Just return the reference. There is no need to dereference the whole hash like you are doing in your examples:
my $result = some_function_that_returns_a_hashref;
say "Foo is ", $result->{foo};
say $_, " => ", $result->{$_} for keys %$result;
etc.
I have never seen anyone pass in empty references to hold the result. This is Perl, not C.
这篇关于从函数返回哈希的最佳Perl练习是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!