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

I have below code, what is 2nd line matching?
$_=$filename; m#/([^/]*)$#; $outfile=$1;
Thanks
Rao

Replies are listed 'Best First'.
Re: what it matches m##?
by toolic (Bishop) on Feb 26, 2016 at 16:01 UTC
    m#/([^/]*)$#;

    Tip #9 from the Basic debugging checklist: YAPE::Regex::Explain. But, due to some limitations, I had to give the tool a little help:

    The regular expression: matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching \n) (matching whitespace and # normally): ---------------------------------------------------------------------- / '/' ---------------------------------------------------------------------- ( group and capture to \1: ---------------------------------------------------------------------- [^/]* any character except: '/' (0 or more times (matching the most amount possible)) ---------------------------------------------------------------------- ) end of \1 ---------------------------------------------------------------------- $ before an optional \n, and the end of the string ---------------------------------------------------------------------- ) end of grouping ----------------------------------------------------------------------

    Customarily, // are used as delimiters, but since it wants to match /, alternate delimiters are used (##) to avoid excessive escaping.

    See also:

Re: what it matches m##?
by neilwatson (Priest) on Feb 26, 2016 at 18:07 UTC

    Sometimes re debug can help:

    #!/usr/bin/perl use strict; use warnings; use re 'debug'; m#/([^/]*)$#; neil@neptune ~/src/perltest $ ./redebug.pl Compiling REx "/([^/]*)$" Final program: 1: EXACT </> (3) 3: OPEN1 (5) 5: STAR (17) 6: ANYOF[^/][{above_bitmap_all}] (0) 17: CLOSE1 (19) 19: SEOL (20) 20: END (0) anchored "/" at 0 floating ""$ at 1..9223372036854775807 (checking anc +hored) minlen 1 Use of uninitialized value $_ in pattern match (m//) at ./redebug.pl l +ine 7. Freeing REx: "/([^/]*)$"

    Neil Watson
    watson-wilson.ca

Re: what it matches m##?
by ExReg (Priest) on Feb 26, 2016 at 17:42 UTC

    The [^/] means anything not a /. The * means 0 or more of those characters. The $ means at the end of the line. So the whole thing will match any characters at the end of the line that are not /'s. Typically if you have a filename with its path, this will capture everything after the last slash: the filename.