in reply to Return value of a sub

The construct sub BLOCK creates an anonymous sub (aka a code reference or "coderef"); it doesn't call the created sub in any fashion (you'd need to do something along the lines of (sub {$str =~ /abc/})->() using your example). As the coderef is always a logically true value the test always passes.

The cake is a lie.
The cake is a lie.
The cake is a lie.

Replies are listed 'Best First'.
Re^2: Return value of a sub
by elTriberium (Friar) on Jul 07, 2009 at 19:17 UTC
    Thanks a lot (also to FunkyMonk). This perfectly answers my question. I think my confusion arose from the fact that the lives_ok test of Test::Exception also accepts these type of test constructs (copy & pasted directly from the CPAN site):
    lives_ok( sub { $file = read_file('test.txt') }, 'file read' );
      I think my confusion arose from the fact that the lives_ok test of Test::Exception also accepts these type of test constructs.
      Now that that's cleared up, you might be interested why Test::Exception requires subroutine references: it wouldn't be possible to catch the exception thrown otherwise (well, actually you could hack around that, but it wouldn't be as reliable and it would probably mess up the code flow). Inside the Test::Exception code there's probably something like eval { $coderef->() } # now do something with $@.

      All of the Test::Exception test functions also allow you to leave off the "sub", and instead just use curly braces, but that's really just a convenience made possible by the often misunderstood prototype facility; you're still passing a subroutine reference as the first argument.