Jasper has asked for the wisdom of the Perl Monks concerning the following question:

I was writing some tests today, and used a construct I'm absolutely sure I've used before
$self->assert($case =~ /test text/, "warning message here");
I was perplexed, because this test was passing, even when a test further down the line revealed that it should have failed.

Eventually I changed it to:
my $result = $case =~ /test text/; $self->assert($result, "warning message");
And all was well. Must be something to do with the list context of the match in a failure case returning nothing, and the tested argument being the warning message. Is there a better way to avoid this? Is there a better way to test things like this? I've left my last job, and, as I say, I'm sure I've left UXBs of this kind there.

Replies are listed 'Best First'.
Re: Trap in Test::Unit::Assert? Avoidance
by Joost (Canon) on Mar 10, 2005 at 13:08 UTC
      Yes, that worked fine, and I did try that before the assignment to result. I thought the assignment was probably more readable...
Re: Trap in Test::Unit::Assert? Avoidance
by Anonymous Monk on Mar 10, 2005 at 13:05 UTC
    A failed match in list context returns an empty list. So your first line was equivalent to:
    $self->assert("warning message here");
      Yes, absolutely right. My mistake was that I thought a straight match returned a scalar value unless it had //g, or matching parens in the regexp. Live and learn, I suppose.
        Nothing returns a scalar in list context. If it's in list context, it will return a list. Even if it's a single element list. ;-)

        Note that a failing regex in list context returning anything but an empty list would be very inconvenient, as this code is common:

        if (my @matches = $var =~ /PATTERN/) { # match } else { # did not match }
        If the failing match would return undef, 0, or the empty string, the result of the assignment becomes true (because a list assignment in scalar context returns the number of things on the RHS of the assignment).