Peeter Joot's (OLD) Blog.

Math, physics, perl, and programming obscurity.

perl implicit matching operator.

Posted by peeterjoot on August 26, 2010

Perl can regularly surprise you with many ways of doing the same thing. I’d seen the following fragment of a script and thought “how can that work … there’s no match operator”.

if ( $CC =~ "xlC|xlc" )
{
  # stuff.
}

What I’d expected is a match // operator, or one that used explicit delimiters such as m@@, as in one of:

if ( $CC =~ /xlC|xlc/ )
{
  # stuff.
}

# or

if ( $CC =~ m@xlC|xlc@ )
{
  # stuff.
}

I’d had the urge to “correct” this incorrect if condition, but a small experiment confirms that this code actually worked as intended:

$CC = "/blah/xlC" ;
#$CC = "/blah/gcc" ;

if ( $CC =~ "xlC|xlc" )
{
print "m\n" ;
}

No explicit match delimited expression is required. It appears that the context of the binding operator is enough to convert a subsequent string into a regular expression. I think I still like doing it explicitly better, perhaps just since that’s how I’ve seen it done the most.

Advertisements

2 Responses to “perl implicit matching operator.”

  1. Dave said

    Interesting! It is documented, once you know to look for it:

    http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators

    “If the right argument is an expression rather than a search pattern, substitution, or transliteration, it is interpreted as a search pattern at run time. Note that this means that its contents will be interpolated twice”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: