|Just another Perl shrine|
Perl Idioms Explained - @ary = $str =~ m/(stuff)/gby tachyon (Chancellor)
|on Sep 15, 2003 at 12:53 UTC||Need Help??|
Consider that you want a regex to find lots of things in a string and store them into an array. Perl has a very convenient idiom for this:
If you are after a single match you use a scalar in list context as the L-VALUE ie
Note if you forget the ( ) around $scalar and you get a match $scalar will contain the integer value 1 so don't forget the ( ). The ( ) gets you list context which you need.
Anyway, although this might not make a lot of sense at first glance it is really very simple. If we had just this:
then we would expect our code to print 'stuff' if the string contained the literal 'stuff' as this gets captured into $1. The addition of /g means the $1 will sequentailly contain 'stuff' EVERY time $str =~m/(stuff)g is true ie 0..n times. Now if we know that a regex is a valid R value in an expression, we know we can write L-VALUE = R-VALUE so we can understand that:
In array context we get all the matches into our array. So for example you can do:
This is a reasonably reliable and quick way to extract all the <a...href=...> links from HTML. Although you can certainly use HTML::LinkExtor or any of the other HTML::Parser based widgets there are times when you want to say extract all the links that look like:
A carefully chosen regex can extract exactly what you want, without any excess, as you can make it match a specific link subset with ease. Using this idiom you can grok the matches into an array in one elegant line of Perl.....
The uses are of course only limited by your imagination. Using ^ and /m you can do things like extract a specific field from a space separated data set:
As always YMMV and you should pick the best hammer to drive the nail at hand.
Technical inaccurary removed. For the details on what happens if you put a scalar on the LHS of this idiom see this where bart gets to poke fun at me for making an untested assumption and my pitiful excuses here and a round about hack....