App-InteractivePerlTutorial/lib/App/InteractivePerlTutorial/Chapter/Smartmatch/Smartmatch.pm
package App::InteractivePerlTutorial::Chapter::Smartmatch::Smartmatch;
use 5.014000;
use strict;
use warnings;
our $VERSION = '0.000_001';
use constant TEXT => 'Smart Matching';
1;
__DATA__
=encoding utf-8
=head1 Smart matching
Basically, smart matching(C<~~>) look at both his operators and decides what to do with them.
=head3 Table for smart match operations for pairs of operands
Example Type of match
------- -------------
%x ~~ %y hash keys identical
%x ~~ @y or @x ~~ %y at least one key in %x is in @y
%x ~~ /text/ or /text/ ~~ %y at least one key matches pattern
'text' ~~ %x exists $x{text}
@x ~~ @y arrays are the same
@x ~~ /text/ at least one element in @x matches pattern
$name ~~ undef $name is not defined
$name ~~ /text/ pattern match
123 ~~ ’123.0’ numeric equality with numeric like string
’text’ ~~ ’text’ string equality
123 ~~ 456 numeric equality
For example:
if ( 1 ~~ 'zero+1' ) { say 'hi' }
if ( 'zero+1' ~~ 1 ) { say 'bye' }
will only print 'hi'. This is because in the first case, since the first argument is a number, the ~~ will be the equivalent with the == and will transform the second argument into a number. In the second case, the first argument is a string so the ~~ operator will be equivalent of the eq and so will transform number 1 in string '1'.
~~ is very useful in the cases from the first 6 lines of the list above. For example writing a code which checks if any key from hash %PC matches 'virus' and prints it would take:
my $corrupt_file = 0;
foreach my $file ( keys %PC ) {
next unless $file = /virus/;
$corrupt_file = $file;
last;
}
if ( $corrupt_file ) { say "WARNING! I found a virus on your PC. It's in $corrupt_file" }
instead of just:
if( /virus/ ~~ %PC ) { say 'WARNING! I found a virus on your PC.' }
=cut