Dave Scotese
Dave Scotese

Reputation: 546

What Perl matching regexp nuances can cause headaches?

This code failed to identify any of the keys it appears to identify:

if( $key =~ /upsf|free|ground|sla|pickup|usps/ )

So I changed it to :

    if( $key eq 'upsf' || $key eq 'free' 
    || $key eq 'ground' || $key eq 'sla' 
    || $key eq 'pickup' || $key eq 'usps' )

They look to me like they are functionally equivalent, so I'm trying to figure out why the first one failed. It's Perl under XAMPP on Windows 7, but it's also Perl under Apache2 on a Linux box.

This prints "shelf it" - both on Windows and Linux.

$key = 'upsf';
if( $key =~ /^(upsf|free|ground|sla|pickup|usps)$/ ) {
    print 'ship it';
} else {
    print 'shelf it';
}

Upvotes: 2

Views: 112

Answers (3)

Dave Scotese
Dave Scotese

Reputation: 546

My Bad!

This code is executed by ClickCart Pro, which reads it from a file and preprocesses it like this:

$custom_script_code =~ s/\`/\'/gs;
$custom_script_code =~ s/\|\|/%7C%7C/g;
$custom_script_code =~ s/\|/ /gs;
$custom_script_code =~ s/%7C%7C/\|\|/g;
$custom_script_code =~ s/system/System/gs;
$custom_script_code =~ s/exec/Exec/gs;
$custom_script_code =~ s/die/Die/gs;

So the pipes are removed by the third statement here. Thanks Kryptronics! (sarcasm) perreal's comment has been plussed. I shouldn't get any points for this. Sorry I wasted everyone's time!

Upvotes: 0

Ωmega
Ωmega

Reputation: 43683

How about this one:

if ($key =~ /^(?:upsf|free|ground|sla|pickup|usps)$/) {
  # ...
} else {
  # ...
} 

Upvotes: 0

ChrisSM
ChrisSM

Reputation: 90

They're not equiv, as the comparison operator in the first is "=~" ("contains"), where in the second it is "eq" ("explicit match, equals").

How exactly did the first one fail? What was your test value for $key?

$key = 'xxx';
if( $key =~ /upsf|free|ground|sla|pickup|usps/ ) {
    print 'ship it';
} else {
    print 'shelf it';
}

will print 'shelf it'. Whereas $key='xusps' , for example, will print 'ship it', match via '=~' operator ("contains"), which may not be your goal.

Upvotes: 3

Related Questions