Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks
I have this code that does a match on a link, it works, but if I try to test the matching on a IF statement the IF does work, I just need to know where the regular expression is not matching as far as the IF statement sees it.
Code:
my $test_match = "D:/newdir/cgi-bin/testbin/errors/"; #Here it will match just fine $test_match =~/(.*?)\/([^\/]+)$/; print "<br>*****$1*****$2****<br>";exit; #But in here the if doesn't, it will go to the ELSE, why? if($test_match =~/(.*?)\/([^\/]+)$/){ print "<br>^^^^$1^^$2^^^^<br>";} else{ print "No Match"; } exit;

Thanks for the Help!

Replies are listed 'Best First'.
Re: Regular Expressions, IF, Issue
by Fletch (Bishop) on Apr 21, 2006 at 14:51 UTC

    Erm, I run that and I see nothing between the "*"s because the first doesn't match (since there's a trailing "/" you don't account for).

    Perhaps if you stepped back and explained what you were trying to do as well it might help (and someone might could point you at something like File::Basename instead).

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Regular Expressions, IF, Issue
by japhy (Canon) on Apr 21, 2006 at 15:00 UTC
    Your first regex does not match against $test_match, because $test_match does not end in a non-/ character (which your regex requires). If $1 and $2 are displaying anything, they are displaying the previous values held by them. (They do not get set to undef when a regex fails, as is documented.)

    In addition to this, the regex's beginning is needlessly ungreedy. /(.*)\/([^\/]+)$/ works the same way as yours, but is much faster. And consider using a different delimiter for your regex; m{(.*)/([^/]+)$} is much easier on the eyes!

    I second the notion that you probably want to use File::Basename.


    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: Regular Expressions, IF, Issue
by wedgef5 (Scribe) on Apr 21, 2006 at 15:01 UTC
    The first match doesn't work. Using warnings will tell you that $1 and $2 are uninitialized. It's not clear to me what you're trying to accomplish here. Perhaps a bit more explanation would help.
      sorry didn't explain well, trying to match the path even if it's shorter or not.
        This works now!
        #!/perl/bin/perl -w use strict; use warnings; use CGI qw/:standard/; use CGI::Carp qw(fatalsToBrowser); print header(); my $test_match = "D:/newdir/cgi-bin/testbin/errors/cgi-bin/testbin/"; #Here it will match just fine #$test_match =~/(.*?)\/([^\/]+)$/; $test_match =~/(.*)\/([^\/]+)\/$/; print "<br>*****$1*****$2****<br>"; #But in here the if doesn't, it will go to the ELSE, why? if($test_match =~/(.*?)\/([^\/]+)\/$/){ print "<br>^^^^$1^^$2^^^^<br>";} else{ print "No Match"; }