Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of ~~ in Perl

Tags:

perl

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

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

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

like image 578
dres Avatar asked Jul 31 '14 12:07

dres


2 Answers

You can also use List::Util (newer versions of this module only) 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 doesn't need the experimental smartmatching.

like image 87
Leeft Avatar answered Sep 28 '22 08:09

Leeft


unless == if not

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

Note: Smart matching is experimental in perl 5.18+. See Smart matching is experimental/depreciated in 5.18 - recommendations? So use the following instead:

print "is not in\n" unless grep { $_ eq 'duhs' } @arr;
like image 21
Miguel Prz Avatar answered Sep 28 '22 09:09

Miguel Prz