I try match syntax using Syntax::Keyword::Match
Syntax::Keyword::Match is a module to enable match syntax in the current Perl by Paul Evans who is one of the current Perl Steering Councils. See perlgov about the Perl Steering Council.
Syntax::Keyword::Match Examples
Syntax::Keyword::Match Examples
Number matching
Number matching. Match syntax is similar as a switch syntax of C language.
use v5.14; use warnings;use Syntax::Keyword::Match;
my $n = 4;
match($n : ==) {
case(1) { say "It's one" }
case(2) { say "It's two" }
case(3) { say "It's three" }
case(4),
case(5) {
say "It's four or five"
}
default { say "It's something else" }
}
Output:
It's four or five
Compared to current Perl, it is shorter and can be written without duplication.
use v5.14; use warnings;my $n = 4;
if ($n == 1) {
say "It's one";
}
elsif ($n == 2) {
say "It's two";
}
elsif ($n == 3) {
say "It's three";
}
elsif ($n == 4 || $n == 5) {
say "It's four or five";
}
else {
say "It's something else";
}
For integers, performance optimization may also be possible using a jump table or a binary tree.
String matching
String matching. Match syntax has also string matching.
use v5.14; use warnings;use Syntax::Keyword::Match;
my $n = 'a4';
match($n : eq) {
case('a1') { say "It's one" }
case('a2') { say "It's two" }
case('a3') { say "It's three" }
case('a4'),
case('a5') {
say "It's four or five"
}
default { say "It's something else" }
}
Output:
It's four or five
Regex matching
Regex matching. Match syntax has also regex matching.
use v5.14; use warnings;use Syntax::Keyword::Match;
my $n = 'a4bbbb';
match($n : =~) {
case(/a1/) { say "It's one" }
case(/a2/) { say "It's two" }
case(/a3/) { say "It's three" }
case(/a4/),
case(/a5/) {
say "It's four or five"
}
default { say "It's something else" }
}
Output:
It's four or five
What I feel using Syntax::Keyword::Match
Personally, I feel number, string, regex matching is enough completed at production level(although Paul said it isn't enough yet).
I'm looking forward to match syntax.
Is this mean we will discard now experimental switch sytax?
this looks like useful, thank you:)
Hi, glycine
Anything haven't been officially decided yet, but I will write about the atmosphere I feel.
The current switch feature is too complex based on the smart match operator.
They want to introduce an easy-to-understand switch feature. This is match feature.
They would like the match feature to be used as an alternative to the current experimental switch feature if the match feature is released.
The current switch feature is likely to be unrecommend. I'm not sure if it will be deprecated.