Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching in PERL ending with period "."

Tags:

perl

I am doing the pattern matching as below. But I am not getting the proper output. Please suggest the correct code to get the correct output.

code

#! /usr/bin/perl -w

my $subString = "1.3.6.1.2.1.26.2.1.1.1.";
my $wholeString = "1.3.6.1.2.1.26.2.1.1.12.1";

 if ($wholeString =~ m/^$subString/)
{
print "matched string is : $&\n";
print "Wrong!!!!\n";
}
else
{
print "matched string is : $&\n";
print "Right!!!!!\n";
}

Actual Output: matched string is : 1.3.6.1.2.1.26.2.1.1.12 Wrong!!!!

Expected Output: matched string is : 1.3.6.1.2.1.26.2.1.1.1. Right!!!!!

What should I change in the code to get the expected output? Please

like image 203
YVRAO Avatar asked Jan 24 '23 16:01

YVRAO


2 Answers

The dot has a special meaning in a regex - it means "match any character here". So the ".1." at the end of your substring is quite happy to match the ".12" in your test string.

To remove the special meaning of dot (and all other special characters) you can use the \Q escape sequence.

if ($wholeString =~ m/^\Q$subString/)

But (as has already been pointed out in the comments), a regex match is probably not the right tool here. You probably need the index() function.

if (index($wholeString, $subString) == 0)
like image 122
Dave Cross Avatar answered Jan 31 '23 05:01

Dave Cross


. matches any character in a regex and it looks like you want to check if $wholeString starts with $subString without regex matching. This can be done using substr:

if(substr($wholeString, 0, length($subString)) eq $subString) {
    # $wholeString starts with $subString
} else {
    # $wholeString does not start with $subString
}
like image 42
Ted Lyngmo Avatar answered Jan 31 '23 05:01

Ted Lyngmo