3 ms·
given and when are actually separate constructs, useful individually. given sets the topic ($_) to its argument for the scope of the block, and when smartmatch
by tene 16y ago
given and when are actually separate constructs, useful individually. given sets the topic ($_) to its argument for the scope of the block, and when smartmatches its argument against the topic (in most cases, mostly when it looks like the argument is a single value). This means that you can use when in any construct with $_ set. The other common place I use this is with iteration.
for (@hosts) {
when (@special) {
...
}
when (/primary/) {
...
}
when (/standby/) {
...
}
default {
...
}
}
As well, when uses a value-based comparison called 'smartmatch', so it's more than a simple equality test like switch/case in C. Smartmatching a scalar against a hash tests for 'exists $hash{$_}'. Smartmatching a scalar against an array does a grep, returning all the items in the array that smartmatch against the value. Smartmatching an array against an array does a recursive smartmatch against pairs of array values. You can also customize smartmatch behaviour for your own classes, by overriding the ~~ operator.
Check the 'perlsyn' man page for the full set of smartmatch behaviours for core types.
http://perldoc.perl.org/perlsyn.html#Smart-matching-in-detail http://perldoc.perl.org/perlsyn.html#Smart-matching-in-detai...
http://perldoc.perl.org/perlsyn.html#Switch-statements http://perldoc.perl.org/perlsyn.html#Switch-statements
I hope this answered your question.