in reply to Why can't $` $& $' be enabled on a per-regex basis?

perlvar:

$` is the same as "substr($var, 0, $-[0])" $& is the same as "substr($var, $-[0], $+[0] - $-[0])" $' is the same as "substr($var, $+[0])"
So:
sub prematch (;$) { substr((@_ ? $_[0] : $_), 0, $-[0]) } sub match (;$) { substr((@_ ? $_[0] : $_), $-[0], $+[0] - $-[0]) } sub postmatch (;$) { substr((@_ ? $_[0] : $_), $+[0]) } my $foo = 'Hello, world!'; $foo =~ /o, w../; $\ = "\n"; print prematch($foo); print match($foo); print postmatch($foo); =head2 C<prematch>, C<match>, C<postmatch> Like C<$`>, C<$&> and C<$'>, but not slowing down, and needing a single argument: the string on which the most recent regex was performed. Uses C<$_> when no argument is given. =cut
Update: s/the variable on which/the string on which/

- Yes, I reinvent wheels.
- Spam: Visit eurotraQ.

Replies are listed 'Best First'.
(tye)Re: Why can't $` $& $' be enabled on a per-regex basis?
by tye (Sage) on Aug 10, 2002 at 16:39 UTC

    Be sure to note that it doesn't work for substitutions:

    sub prematch (;$) { substr((@_ ? $_[0] : $_), 0, $-[0]) } sub match (;$) { substr((@_ ? $_[0] : $_), $-[0], $+[0] - $-[0]) } sub postmatch (;$) { substr((@_ ? $_[0] : $_), $+[0]) } my $foo = 'Hello, world!'; $foo =~ s/l+/r/; print "prematch(",prematch($foo),")\n"; print "match(",match($foo),")\n"; print "postmatch(",postmatch($foo),")\n"; print "`(",$`,")\n"; print "&(",$&,")\n"; print "'(",$',")\n";
    produces
    prematch(He) match(ro) postmatch(, world!) `(He) &(ll) '(o, world!)

            - tye (but my friends call me "Tye")