这个问题在这里已经有了答案:
Perl赋值与假占位符 4答案假设我有一个返回固定长度列表的函数foo ,并将返回的列表分配给少数变量,如下所示:
($duck, $lemonade, $stand, $grapes) = foo($waddle);但事实证明,我实际上并不想要$lemonade 。 我可以用下划线替换它来说我不需要值(它在其他一些编程语言中用于此目的),但由于它在Perl中具有隐含的特殊含义,我认为它可能是混乱的完全不好。
Perl是否有这种“一次性”变量的约定,或者是否有更多的Perly(perlish?)方式? 或者更确切地说,鉴于这是Perl,还有其他方法吗?
This question already has an answer here:
Perl assignment with a dummy placeholder 4 answersLet's say I have a function foo which returns a fixed-length list, and I assign the returned list to a handful of variables like so:
($duck, $lemonade, $stand, $grapes) = foo($waddle);But then it turns out that I don't actually want $lemonade. I could replace it with the underscore to say that I don't need the value (it's used for this purpose in a few other programming languages), but since it has an implicit special meaning in Perl, I thought it might be anything from confusing to outright bad.
Does Perl have a convention for such "throwaway" variables, or is there a more Perly (perlish?) way of doing this? Or rather, given this is Perl, what other ways are there?
最满意答案
你可以做这样的事情来明确你丢弃的值:
use strict; use warnings; sub foo { return ( 1..4 ); } my ( $one, undef, $three, undef ) = foo(); print "$one $three\n"; # prints "1 3"You can do something like this to be explicit about which values you are throwing away:
use strict; use warnings; sub foo { return ( 1..4 ); } my ( $one, undef, $three, undef ) = foo(); print "$one $three\n"; # prints "1 3"更多推荐
发布评论