I stumbled across this problem today, while looking at some code using Test::Simple. The following test always passes, even if the string doesn't match:
ok(sub{$str =~ /abc/}, "string matches");
Now I can easily rewrite this test to:
Now it will only pass in case the string really matches. Problem solved.ok($str =~ /abc/, "string matches");
But the question I'm really asking myself here is why did it pass in the first time? I wrote this simple example program:
The output is:#!/usr/bin/perl use strict; use warnings; (sub {my $str = "aaa"; $str =~ m/abc/}) ? print "sub ok\n" : print "su +b fail\n"; get_return() ? print "return ok\n" : print "return fail\n"; sub get_return { my $str = "aaa"; $str =~ m/abc/; }
Can someone help me understand why the result of the anonymous (?) sub is true and the result of the regular sub is false?sub ok return fail
In reply to Return value of a sub by elTriberium
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |