re::ampersand - Perl pragma to alter $& support in regular expressions
# see examples
When Perl sees you using $`, $&, or $', it has to prepare these variable after every successful pattern match. This can slow a program down because these variables are "prepared" by copying the string you matched against to an internal location. This copying is also how $DIGIT variables are made accessible, but that only occurs on a per-regex basis: if a regex has capturing parentheses, the string will be copied, otherwise it will not be.
This pragma allow you to turn on and off the support for $& and friends in blocks of your code.
Your program will run the same way it did before if you do not use this pragma. Default behavior has not been changed.
You can enforce support for $& and friends with use re::ampersand 'capture', which makes all regexes set $& if they are successful. You can leave off the 'capture' argument.
You can turn off support for $& with use re::ampersand 'no_capture', which stops all regexes (that don't have capturing parentheses) from setting $&. Any regex with capturing parentheses will always have support for $& because of the mechanism that provides $DIGIT variables.
#!/usr/bin/perl -w
"Perl" =~ /Pe/;
{ use re::ampersand; "Perl" =~ /rl/ and print "<$&>\n"; # <rl> }
# $& has not been seen yet! "Perl" =~ /rl/ and print "<$&>\n"; # <>
#!/usr/bin/perl -w
# regexes set $& "Perl" =~ /(?<=.)./ and print "<$&>\n"; # <e>
{ use re::ampersand 'no_capture'; # matching on a string you'd rather not have copied! $huge_string =~ /a+bc+/ and print "<$&>\n"; # <> }
# regexes set $& "Perl" =~ /.(?!..)/ and print "<$&>\n"; # <r>
Do not try no re::ampersand unless you are aware of the consequences! If you do this, any $& found in the no re::ampersand block of code will cause the ``seen $&'' flag to go on for the normal program. That means the following code produces the output denoted by the comments:
"abc" =~ /a/ and eval q{ print "<$&>" }; # <a> { no re::ampersand; "abc" =~ /b/ and print "<$&>"; # <b> }
When your program is being compiled, the $& in the no re::ampersand block sets the ``seen $&'' flag in your program, which means that when the "abc" =~ /a/ regex is executed, it will set $&.
Efforts are currently underway to fix this behavior.
Jeff japhy Pinyan, japhy@pobox.com.
_____________________________________________________
Jeff[japhy]Pinyan:
Perl,
regex,
and perl
hacker.
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;
|
---|