Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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

( #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? 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

Comment on Answer: How do I get what is to the left of my match?
Download Code
RE: Answer: How do I get what is to the left of my match?
by tye (Cardinal) 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?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2014-04-19 15:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (483 votes), past polls