[英]How can I skip elements in Perl list assignment akin to Haskell pattern matching?
In Haskell (and various other functional programming languages), pattern matching can be used to assign specific elements of a list while discarding others: 在Haskell(和各种其他函数式编程语言)中, 模式匹配可用于分配列表的特定元素,同时丢弃其他元素:
Prelude> let [x, _, z] = "abc"
Prelude> x
'a'
Prelude> [z, x]
"ca"
Note that ' _
' is not a variable and hasn't been assigned anything: 请注意,'
_
'不是变量,并且未分配任何内容:
Prelude> _
<interactive>:5:1: Pattern syntax in expression context: _
For an Irssi script, written in Perl, I want to do a similar thing and discard the 2 nd element of ' @_
' (ie not assign it to anything): 对于用Perl编写的Irssi脚本,我想做类似的事情并丢弃'
@_
'的第二个元素(即不将它分配给任何东西):
my ($message, _, $windowItem) = @_;
This fails with the error message: “ Can't declare constant item in "my" at [...]overlength_filter.pl line 17, near ") ="
” 这失败并显示错误消息:“
Can't declare constant item in "my" at [...]overlength_filter.pl line 17, near ") ="
”
So what is the Perl equivalent of this underscore wildcard? 那么这个下划线通配符的Perl等价物是什么?
只需将其分配给undef
。
my ($message, undef, $windowItem) = @_;
你也可以拿一个数组:)
my( $message , $winItem ) = @_[ 0, 2];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.