Come for the quick hacks, stay for the epiphanies. | |
PerlMonks |
Re: simple regexp questionby jbert (Priest) |
on Nov 21, 2007 at 10:25 UTC ( [id://652096]=note: print w/replies, xml ) | Need Help?? |
And to elaborate slightly on why the given solutions work, parens ( ) in a regexp capture their contents to the special variables $1, $2, ....
These are numbered according to the order of the capture groups (as ordered by their left hand paren). You can use them (as shown) in the right-hand-side of a search and replace, but they're also valid perl variables which you can make use of after a substitution or ordinary match: Since regexp could in principle overwrite these global special variables, you should make use of them immediately after the regexp and/or save off their values into more appropriateley named vars. (e.g. if you call a subroutine, you don't know if that sub has done a regex and overwritten them). Since parens are used for purposes other than grouping (e.g. to have alternating choices (foo|bar|baz), you can use a "non-capturing group", with (?:). Search for 'captur' in perlre for more gory details.
In Section
Seekers of Perl Wisdom
|
|