NotProud has asked for the wisdom of the Perl Monks concerning the following question: ⭐ (regular expressions)
Thanks"left center right" =~ /center/; print "<br>Left: <$`>\n"; print "<br>Match: $&\n"; print "<br>Right: <$'>\n";
Originally posted as a Categorized Question.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How do I get what is to the left of my match?⭐
by tye (Sage) on Sep 26, 2000 at 08:33 UTC | |
Note that if you ever even mention $`, $&, or $', anywhere, then all regular expressions anywhere in that run of Perl will be not-insignificantly slower. So their use is strongly discouraged in code that might be reused or where performance is important. This is because using those anywhere forces each regex to make copies of those strings every time, even though most of those copies will never be used (if Perl ever needs them then Perl can't predict when it might need them and so must always make the copies). But the latest version of Perl adds an alternate way to get this type of information, @- and @+. Here is a sample of how to use them: At the time of this writing, perlvar isn't recent enough to mention @- and @+. But if you have a version of Perl recent enough to have @- and @+, (Perl 5.6.0 or later) then your perlvar.pod will also include documentation on them. If you can't find perlvar.pod then enter the command perldoc perlvar or cd to your perl lib directory and there should be a pod directory that contains that file. These pod files contain some simple "mark-up" codes but are designed to be easy for humans to read. (You can read perlpod.pod for more information on the mark-up language.) - tye | [reply] [d/l] |
by tye (Sage) on Sep 26, 2000 at 08:49 UTC | |
| [reply] | |
|
Re: How do I get what is to the left of my match?⭐
by fundflow (Chaplain) on Sep 26, 2000 at 05:42 UTC | |
| [reply] [d/l] |
by chipmunk (Parson) on Nov 28, 2000 at 03:29 UTC | |
Keep in mind that /(center)/ will match the first occurence of 'center' in the string, while /(.*)(center)(.*)/ will match the last occurence of center (leaving aside for the moment the issue of newlines). This might be preferred:On the other hand, sometimes using $` et al. is appropriate. | [reply] [d/l] |
|
Re: How do I get what is to the left of my match?
by lima1 (Curate) on Oct 04, 2007 at 16:16 UTC | |
Note that this and the previous solutions are significantly slower than using the matchvariables &`, $& and $'. However, as tye mentioned, these variables will slow down EVERY other regular expression without capturing parentheses. The following benchmark (searching a short (11 characters or base pairs) DNA sequence in a 2000 bp DNA sequence) shows the results of a comparison of all four solutions: Note that this benchmark uses match variables and thus slows down all four solutions. The results without the match variable solution are:
Appendix: Source code of the benchmark
| [reply] [d/l] [select] |