多个赋值中的丢失变量[重复](Throwaway variables in multiple assignment [duplicate])

编程入门 行业动态 更新时间:2024-10-18 21:26:05
多个赋值中的丢失变量[重复](Throwaway variables in multiple assignment [duplicate])

这个问题在这里已经有了答案:

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 answers

Let'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"

更多推荐

本文发布于:2023-08-07 11:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464475.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   赋值   变量   Throwaway   duplicate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!