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:
@ary = $str =~ m/(stuff)/g;
If you are after a single match you use a scalar in list context as the L-VALUE ie
($scalar) = $str =~ m/(this)/;
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:
$str =~ m/(stuff)/; print $1
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:
@all_the_matches = $str =~ m/(stuff)/g;
In array context we get all the matches into our array. So for example you can do:
@links = $html =~ m/<a[^>]+href\s*=\s*["']?([^"'> ]+)/ig;
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 CLASS="blah" HREF="foo.com">
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:
$data = ' f1 f2 f3 f4 f5 f6 f7 f8 f9 '; @second = $data =~ m/^\S+\s+(\S+)/mg; print "@second";
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....