Using a Variable as a Match Expression

Kewl Splitpath One Liner Regex

Check out this splitpath command:

my($text) = "/etc/sysconfig/network-scripts/ifcfg-eth0";
my($directory, $filename) = $text =~ m/(.*\/)(.*)$/;

print "D=$directory, F=$filename\n";

Is that cool or what?

Using a Variable as a Match Expression

You can use a variable inside the match expression. This yields tremendous power. Simply place the variable name between the forward slashes, and the expression will be sought in the string. Here’s an example:

#!/usr/bin/perl -w
# use strict;

sub test($$)
	my $lookfor = shift;
	my $string = shift;
	print "\n$lookfor ";
	if($string =~ m/($lookfor)/)
		print " is in ";
		print " is NOT in ";
	print "$string.";
		print "      <$1>";
	print "\n";

test("st.v.", "steve was here");
test("st.v.", "kitchen stove");
test("st.v.", "kitchen store");

The preceding code produces the following output.

[slitt@mydesk slitt]$ ./

st.v.  is in steve was here.      <steve>

st.v.  is in kitchen stove.      <stove>

st.v.  is NOT in kitchen store.
[slitt@mydesk slitt]$

As you can see, you can seek a regex expression stored in a variable, and you can retrieve the result in $1.

A common mistake people do when using regular expressions is to try to match a variable in your regular expressions.


Code: Perl
$data =~ s!$url!!;

This is going to work properly most of the time. But sometime it won’t behave as expected or you will be experiencing occasional run time errors. For example, if your $url is equal to, the substitution operator is going to fail and exit with an error message.

 "/ nested *?+ in regex..."

The reason for the failure is that you can’t use “++” inside your regular expression. You have to escape them. The variable might include several special variables, which have to be escaped properly. To correct way to implement this substitution is:

Code: Perl
$temp = quotemeta($url);
$data =~ s!$temp!!;

quotemeta() is a standard perl function and it escapes all non-alphanumeric characters in your variable.


Leave a Reply

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

You are commenting using your 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