[Chicago-talk] Probably and easy explanation I'm missing...

Jonathan Rockway jon at jrock.us
Thu Aug 24 13:44:34 PDT 2006


> I realize I'm not as smart as a I once was. I'm confused about the
> following substitution:
>         my $filename   = $GLOBAL{'FILE_NAME'};
>         $filename =~ s/.+\\([^\\]+)$|.+\/([^\/]+)$/$1/;
>
> How does the $1 work in this? Is it necessary? 

$1 is the contents of the (capture).  You're replacing the entire match
with the value of the first capture.  (There are two first captures in
your case, though :)

Let's use a simpler example:

s/(\d+)[.](\d+)/$2$1/;

This will match something like this:

1234.5678

And fill ($1, $2) with ("1234", "5678")

The replacement part then replaces the entire match with "$2$1", yielding:

56781234

Something like

aaaaa1234.5678aaaaaa

will change to

aaaaa56781234aaaaaa.

Anyway, your substitution will change something like "foo\bar" to "bar",
or foo\bar\baz to "baz".  The | chooses between Windows paths and UNIX
paths.

BTW, File::Spec would be a better way to do this.

Finally, you might enjoy using "use re 'debug';" at the top of your
program.  It will give you helpful output like this:

$ perl -Mre=debug -ne 's/foo/bar/g; print;'
Freeing REx: `","'
Compiling REx `foo'
size 3 Got 28 bytes for offset annotations.
first at 1
   1: EXACT <foo>(3)
   3: END(0)
anchored "foo" at 0 (checking anchored isall) minlen 3
Offsets: [3]
        1[3] 0[0] 4[0]
typed> this is a foo bar
Guessing start of match, REx "foo" against "this is a foo bar
"...
Found anchored substr "foo" at offset 10...
Starting position does not contradict /^/m...
Guessed: match at offset 10
Matching REx "foo" against "foo bar
"
  Setting an EVAL scope, savestack=8
  10 <is a > <foo bar>    |  1:  EXACT <foo>
  13 <s a foo> < bar
>    |  3:  END
Match successful!
Guessing start of match, REx "foo" against " bar
"...
Did not find anchored substr "foo"...
Match rejected by optimizer
Not present...
Match failed
result> this is a bar bar
^C

Regards,
Jonathan Rockway


More information about the Chicago-talk mailing list