Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Failed match not stored

by BillKSmith (Monsignor)
on Apr 07, 2025 at 20:09 UTC ( [id://11164618]=perlquestion: print w/replies, xml ) Need Help??

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

The match operator returns an (unspecified)false value when the match fails. Why is that value not stored in this case?
use strict; use warnings; use version '5.38'; use feature 'say'; use Test::More tests=>1; my @arry1 = ('string'=~ m/str/, 'second'); my @arry2 = ('string'=~ m/foo/, 'second'); # no value stored for failed match. is $arry2[1], $arry1[1];

RESULT

not ok 1 # Failed test at tryit2.pl line 10 # got: undef # expected: 'second' # Looks like you failed 1 test of 1.
Bill

Replies are listed 'Best First'.
Re: Failed match not stored
by jwkrahn (Abbot) on Apr 07, 2025 at 20:29 UTC

    In list context a failed match returns an empty list.

    Naked blocks are fun! -- Randal L. Schwartz, Perl hacker
      Thanks for the simple answer. The original problem was more subtle than my example, but in both cases, I failed to recognize the list context.
      Bill
Re: Failed match not stored
by duelafn (Parson) on Apr 08, 2025 at 00:09 UTC

    Thus, you can fix the issue in a couple ways. Explicitly forcing scalar context:

    use Test::More tests=>1; my @arry1 = (scalar 'string' =~ m/str/, 'second'); my @arry2 = (scalar 'string' =~ m/foo/, 'second'); is $arry2[1], $arry1[1];

    or choosing your false value (and implicitly forcing scalar context)

    use Test::More tests=>1; my @arry1 = (('string' =~ m/str/ or 0), 'second'); my @arry2 = (('string' =~ m/foo/ or 0), 'second'); is $arry2[1], $arry1[1];

    Good Day,
        Dean

      I already had a 'workaround' similar to your second solution. I will adopt your first suggestion because it explicitly addresses the real issue rather than working around it.
      Bill

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11164618]
Approved by GrandFather
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (4)
As of 2026-03-06 17:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.