Sumit
Sumit

Reputation: 2023

Need to know logic behind few regular expression

I am having a code as

$wrk = OC192-1-1-1;

@temp = split (/-/, $wrk);

 if ($temp1[3] =~ /101 || 102 /)
{
    print "yes";
} else {
    print "no";
}

Output :

yes

Need to know why this is printing yes. I know for regular expression | is supported for OR operator. But need to know why || is giving as "yes" as output

Upvotes: 3

Views: 143

Answers (3)

mpapec
mpapec

Reputation: 50657

/101 || 102 / regex tries to match '101 ', or '' (empty string), or ' 102 '.

Since empty string can always be matched, it always returns true in your condition.

Upvotes: 7

Vlad
Vlad

Reputation: 1197

In addition to the regex-relevant answer from @anubhava, note that: OC192-1-1-1 is same as 0-1-1-1, which is just "-3", therefore @temp evaluates to ( "", "3" )

And of course there's no such thing as $temp1

Upvotes: 3

anubhava
anubhava

Reputation: 785471

It is because || will make regex match succeed by matching with nothing all the time.

So it is essentially matching $temp1[3] (which doesn't exist) with anyone of the following

  • "101 "
  • ""
  • " 102 "

I added double quotes just for explanation.

Upvotes: 9

Related Questions