
Kenosis
User
Apr 2, 2013, 8:10 AM
Post #6 of 6
(1173 views)
|
The following variables are initialized by a successful regex:
$` Everything prior to matched string $& Entire matched string $' Everything after to matched string Source: perlreref However, the above source says the following about their use:
The use of $` , $& or $' will slow down all regex use within your program. Instead, we're encouraged to use the following:
${^PREMATCH} Everything prior to matched string ${^MATCH} Entire matched string ${^POSTMATCH} Everything after to matched string However, these will not work in the substitution. Instead, the better way to achieve the output you've shown is by using captures:
use strict; use warnings; $_ = "huge dinosaur"; s/(.+?)\K(\w+)$/($1!)$2/; # Now it's "huge (huge !)dinosaur" print "$_\n"; At first glance, the above appears to add an unnecessary layer of complexity, as it's certainly not as easily read as the original regex. However, this will not incur the performance penalty that the original script costs. Here's the regex explained:
s/(.+?)\K(\w+)$/($1!)$2/ ^ ^ ^ ^ ^ ^ ^ | | | | | | | | | | | | | + - Use what was captured in the second group "(\w+)" | | | | | + - Use what was captured in the first group "(.+?)" | | | | + - The end of the line | | | + - Match and capture one or more 'word' characters | | + - Keep everything before the 'word' characters | + - Match and capture one or more of any character (almost), but don't be 'greedy' (the effect of the "?") + - Begin substitution Hope this helps!
|