Opposite ~~ in Perl

Is there an opposite for the ~~ operator in Perl? I used it to map an element in an array like this:

 my @arr = qw /hello ma duhs udsyyd hjgdsh/; print "is in\n" if ('duhs' ~~ @arr); 

Prints is in . This is pretty cool because I don't have to iterate over the entire array and compare each record. My problem is that I want to do something if I do not have a match. I could go to the else side, but I rather found the opposite for `~~ '

+6
source share
2 answers

if == if not

 print "is not in\n" unless ('duhs' ~~ @arr); 

Note. Intelligent matching is experimental in perl 5.18+. See Intelligent matching experimentally / depreciates in 5.18 - recommendations? Therefore, use the following instead:

 print "is not in\n" unless grep { $_ eq 'duhs' } @arr; 
+8
source

You can also use List::Util (only new versions of this module) or List::MoreUtils with any , none and friends.

 use List::Util qw(any none); my @arr = qw /hello ma duhs udsyyd hjgdsh/; say "oh hi" if any { $_ eq 'hello' } @arr; say "no goodbyes?" if none { $_ eq 'goodbye' } @arr; 

While not perl-native, it does not need experimental smartmatching.

+12
source

Source: https://habr.com/ru/post/973165/


All Articles