用于获取数组中最大元素数的 Perl 习惯用法
我想砍掉数组中除了前五个元素之外的所有元素,所以我愚蠢地这么做了:
@foo = @foo[ 0 .. 4 ];
并由衷地称赞自己的聪明才智。但是一旦 @foo
最终只包含三个元素,这种情况就被打破了,因为最后我得到了两个 undef
,而不是一个三元素数组。所以我把它改成了:
@foo = @foo > 5 ? @foo[ 0 .. 4 ] : @foo;
这可行,但有点难看。有没有更好的习惯用法来表达“给我数组前五个元素之前的所有内容?”
I wanted to chop off all but the first five elements of an array, so I stupidly did:
@foo = @foo[ 0 .. 4 ];
and heartily praised my own cleverness. But that broke once @foo
ended up with only three elements, because then I ended up with two undef
s on the end, instead of a three-element array. So I changed it to:
@foo = @foo > 5 ? @foo[ 0 .. 4 ] : @foo;
This works but is kinda ugly. Is there a better idiom for saying "give me everything up to the first five elements of the array?"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以设置数组的最后一个索引来缩短或延长数组。就像您的代码一样,您需要检查以确保您没有创建 undef 元素。
You can set the last index of an array to shorten or lengthen it. Like your code you'll need to check to make sure your not creating undef elements.
如果您不关心突变(由自引用 lhs
@foo
= 引用@foo
暗示),请使用两个参数splice()
,请参阅 perldoc -f splice 了解更多信息信息。然后观察效果:
如果您使用
警告
,我希望您必须检查长度(如 Axeman 的建议)或禁用噪音警告(splice() offset超出数组末尾):If you don't care about mutations (implied by the self-referential lhs
@foo
= something referencing@foo
) use the two-argumentsplice()
, see perldoc -f splice for more info.Then watch the effect:
If you're using
warnings
, and I hope you'll have to check for the length (as in Axeman's suggestion) or disable the noisy warning (splice() offset past end of array):还有另一种方式:
与其他拼接建议不同,这不会触发警告; 5 明确表示“最多 5”。
Yet another way:
Unlike the other suggestion for splice, this doesn't trigger a warning; the 5 explicitly means "up to 5".
这不太优雅,但您可以这样表达:
通用的
min
函数可能看起来更好。但如果你只是想摆脱其他一切,那么你只需要
拼接
其余的:This isn't that graceful, but you can express it like this:
A generalized
min
function might look better.But if you just want to get rid of everything else then you just need to
splice
off the rest: