Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Is this normal

by himik (Acolyte)
on Jan 06, 2012 at 14:44 UTC ( #946606=perlquestion: print w/replies, xml ) Need Help??
himik has asked for the wisdom of the Perl Monks concerning the following question:

Hello. Why this is not returning 0 when the regex is false?

sub TestIt { my ($p1,$p2,$p3,$p4)=@_; print "p1=$p1,p2=$p2,p3=$p3,p4=$p4\n"; } my ($a1,$a2,$a3,$a4)=(1,2,3,4); &TestIt($a1,$a2,$a3=~m/2/,$a4);

when $a3=~m/3/ every thing is ok, but when it is false it is not parsing 0. And the parameters is 1 less. When i use $a2==3 it parse the 0. Can someone explain it to me?

Replies are listed 'Best First'.
Re: Is this normal
by toolic (Bishop) on Jan 06, 2012 at 15:24 UTC
    If you want the match to return 1 if successful, and 0 if it fails, you can use the ternary operator:
    &TestIt($a1,$a2, ($a3 =~ m/2/) ? 1 : 0 ,$a4);
Re: Is this normal
by JavaFan (Canon) on Jan 06, 2012 at 15:20 UTC
    You're making two mistakes:
    1. You're calling the match in list context, so an empty list is returned, reducing the number of passed parameters.
    2. Even when called in scalar context, a non-match does not return 0. It returns the empty string (most Perl build-ins that return either a true or a false value, return 1 or "")
      a non-match does not return 0. It returns the empty string
      Strictly speaking, it returns PL_sv_no, which has both a numerical value of 0 and a string value of "":
      $ perl5140 -MDevel::Peek -e 'Dump scalar(/x/)' SV = PVNV(0x275ee10) at 0xa26500 REFCNT = 2147483647 FLAGS = (IOK,NOK,POK,READONLY,pIOK,pNOK,pPOK) IV = 0 NV = 0 PV = 0x275ee00 ""\0 CUR = 0 LEN = 16


        You are correct. However, the OP is printing out the values, so the string value will be taken.
Re: Is this normal
by roboticus (Chancellor) on Jan 06, 2012 at 14:55 UTC


    I'm guessing that it's because you're calling the m operator in list context rather than scalar context. Perhaps it would work if you try:

    TestIt($a1, $a2, scalar($a3=~m/2/), $a4);


    When your only tool is a hammer, all problems look like your thumb.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://946606]
Approved by toolic
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2018-03-22 01:06 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (272 votes). Check out past polls.