Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

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?

Comment on Is this normal
Download Code
Re: Is this normal
by roboticus (Canon) on Jan 06, 2012 at 14:55 UTC

    himik:

    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);

    ...roboticus

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

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

      Dave.

        You are correct. However, the OP is printing out the values, so the string value will be taken.
Re: Is this normal
by toolic (Chancellor) 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);

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://946606]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2014-12-28 13:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (181 votes), past polls