Home: Perl Programming Help: Regular Expressions:
comparing regex with variable



biswa_pradhan
New User

Oct 29, 2015, 8:29 PM


Views: 7249
comparing regex with variable

I am facing problem while comparing regex with variable.
When I compare directly the output is as expected, But when I am using a variable, its not working fine.
My Snippet with expected output:
...
if ($path =~/D:\\All\\Mine\//)
{
print $printlog "Success \n" ;
}
else
{
print $printlog "Error\n" ;
}
Here output is Success.
But the problem I am getting is when I use a variable instead direct comparision.
...
my $plfolder = "D:\\All\\Mine\/";
if ($path =~/($plfolder)/)
{
print $printlog "Success \n" ;
}
else
{
print $printlog "Error\n" ;
}
Here output is Error.

Please help me with this.


Laurent_R
Veteran / Moderator

Oct 30, 2015, 4:40 AM


Views: 7240
Re: [biswa_pradhan] comparing regex with variable

Hi,
what is the content of $path?

I find the ending "\/" a bit strange in your variable "D:\\All\\Mine\/". I would expect you to look for a backslash rather than a regular slash in a Windows path.

Otherwise, look at the quotemeta operator, which will insert properly all the backslashes as needed, so that you don't have to worry about it.


BillKSmith
Veteran

Oct 30, 2015, 12:59 PM


Views: 7225
Re: [biswa_pradhan] comparing regex with variable

The strange final slash has nothing to do with your problem. (Windows will accept either forward or backward slash)

If you had used "use warnings;", you would have received a message alerting you to the problem. The message is correct, but not very helpful.

Strings are not quite the same as regexes. In your regex, you correctly escape the backslashes because you intend them to be used literally. You escape the forward slash to prevent a conflict with the match delimiter. In your second example, you want to put this regex in a string. In order to put two consecutive backslashes in a string, you must escape both of them. It is not necessary to escape the forward slash, because there is no conflict.

Code
#my $plfolder = "D:\\All\\Mine\/";  
my $plfolder = 'D:\\\\All\\\\Mine/';


A better solution is use the Regex quote like operator (qr).


Code
my $plfolder = qr/D:\\All\\Mine\//;

Good Luck,
Bill