in reply to Making the later front slash "/" optional

First, don't confuse things by using '/' as your "quote like characters" for the regular expression. A regexp can look like this: m//, or you can use a wide variety of other characters, such as m{} or m!!. The reason this is helpful is that if your regexp has any literal '/' in it, you end up having to escape it with a preceding backslash. This leads to the leaning-toothpicks effect: (example) m/\\|\// matches '\' or '/', and does so in a visually confusing way.

Now that we've got that annoyance out of the way, we can use visually clear code. Your objective now is simply to make that trailing slash optional. The character inside of a regexp that means 'optional' is the question mark. So it could look like this:

m{$location/?$}

Now on the other hand, if the expression held in $location actually ends in a slash too, then you're going to need to prepare your regexp with a little more care. Here I'm going to examine $location to see if it ends in a slash, and if it does, append a question mark. Then I'll use that new string as my regular expression.

my $file = 'some_filename'; my $location = 'some_filename/'; $location =~ s{/$}{/?}; # If a trailing / is found, append a ? to it. if( $file ~= m{$location$} ) { # Do your stuff }

Dave

Replies are listed 'Best First'.
Re^2: Making the later front slash "/" optional
by CountZero (Bishop) on May 03, 2011 at 10:12 UTC
    Or perhaps append a trailing slash anyhow to $location and check for one or two trailing slashes?

    m{$location/{1,2}$}

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James