CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

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


New User

Oct 29, 2015, 8:29 PM

Post #1 of 3 (14887 views)
comparing regex with variable Can't Post

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" ;
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" ;
print $printlog "Error\n" ;
Here output is Error.

Please help me with this.

Veteran / Moderator

Oct 30, 2015, 4:40 AM

Post #2 of 3 (14878 views)
Re: [biswa_pradhan] comparing regex with variable [In reply to] Can't Post

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.


Oct 30, 2015, 12:59 PM

Post #3 of 3 (14863 views)
Re: [biswa_pradhan] comparing regex with variable [In reply to] Can't Post

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.

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

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

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

Good Luck,


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives