I’m building a stress-system in Perl for correcting students programming assignments. I built a function check(<boolean>,<congrats-message>,<blame-message>) that is supposed to help me along the way.
When I invoke it as
check(get_option('content-type') eq "text/html","good type", "bad type");
everything is fine. But if I dare to do
check(get_option('content-type') =~ m:text/html:i, "good type", "bad type");
it breaks when the regexp doesn’t find a match. Actually it is then equivalent to a check("good type", "bad type"). I use only $_[0], $_[1] etc. in check() function, and it’s not like I had ‘undef’ as first argument: I can really catch the bug with die unless $#_ == 2.
What’s happening ? I worked it around with
check((get_option('content-type') =~ m:text/html:i && 1), "good type", "bad type");
but I’d love to understand the what and why of this odd situation.
—
sub check {
if ($_[0]) {
$okay++;
print STDERR "^_^ $_[1] ($okay)\n";
} else {
print STDERR ">_< $_[2]\n";
}
return $_[0];
}
eqalways returns true or false, but=~(when in list context) returns “a list consisting of the subexpressions matched by the parentheses in the pattern,”.When you put a list inside another list (e.g. the list of matches inside the list of arguments to the subroutine), they get merged.
If there are 0 matches, you get the 2 other arguments in the list.
If there are 2 matches, you get those 2 matches then the 2 other arguments for a total of 4 arguments.
Your code depends on there being exactly three arguments.