elTriberium has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Return value of a sub
by Fletch (Bishop) on Jul 07, 2009 at 19:11 UTC | |
by elTriberium (Friar) on Jul 07, 2009 at 19:17 UTC | |
by Joost (Canon) on Jul 07, 2009 at 19:31 UTC | |
|
Re: Return value of a sub
by FunkyMonk (Bishop) on Jul 07, 2009 at 19:14 UTC | |
by AnomalousMonk (Archbishop) on Jul 07, 2009 at 19:22 UTC |