Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Answer: How do I get what is to the left of my match?

by tye (Sage)
on Sep 26, 2000 at 08:33 UTC ( #33984=categorized answer: print w/replies, xml ) Need Help??

Q&A > regular expressions > How do I get what is to the left of my match? - Answer contributed by tye

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:

( my $str= "left center right" ) =~ /center/; print "\nLeft: <", substr( $str, 0, $-[0] ), ">\nMatch: <", substr( $str, $-[$#-], $+[$#-] - $-[$#-] ), ">\nRight: <", substr( $str, $+[$#+] ), ">\n"; __END__ This prints: Left: <left > Match: <center> Right: < right>

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

Replies are listed 'Best First'.
RE: Answer: How do I get what is to the left of my match?
by tye (Sage) on Sep 26, 2000 at 08:49 UTC

    Thanks to ar0n for updating the above node. This node is now defunct and should be deleted soon. (:

    Nothing to see here. Move along.

            - tye (but my friends call me "Tye")
Log In?

What's my password?
Create A New User
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2018-05-28 01:43 GMT
Find Nodes?
    Voting Booth?