basics advanced
How to use the smartmatch operator in Perl
Question
How does the ~~ (smartmatch) operator work in Perl 5.10+?
The smartmatch operator performs context-aware comparisons (note: experimental and not recommended for new code):
use v5.10;
use strict;
use warnings;
no warnings 'experimental::smartmatch';
my $value = 42;
my @array = (10, 20, 30, 40, 50);
my %hash = (a => 1, b => 2, c => 3);
# Scalar in array
say "Found" if 30 ~~ @array; # Found
# Regex match
say "Match" if "hello" ~~ /^h/; # Match
# Hash key exists
say "Exists" if 'b' ~~ %hash; # Exists
# Array equality
my @other = (10, 20, 30, 40, 50);
say "Equal" if @array ~~ @other; # Equal
# Recommended alternative: use grep or List::Util
use List::Util 'any';
say "Found" if any { $_ == 30 } @array;
Smartmatch is experimental and its behavior has changed across Perl versions. Use explicit comparisons or List::Util instead.