Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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 2nd element of ‘@_’ (i.e. not assign it to anything):

my ($message, _, $windowItem) = @_;

This fails with the error message: “Can't declare constant item in "my" at [...]overlength_filter.pl line 17, near ") ="

So what is the Perl equivalent of this underscore wildcard?

like image 779
James Haigh Avatar asked Jan 17 '15 02:01

James Haigh


2 Answers

Just assign it to undef.

my ($message, undef, $windowItem) = @_;

like image 69
Chris Charley Avatar answered Nov 12 '22 00:11

Chris Charley


You can also take a slice of the array :)

my( $message , $winItem ) = @_[ 0, 2];
like image 41
optional Avatar answered Nov 12 '22 00:11

optional