I'll take a crack at this one, since it gave me the same kind of problems when I started using regexps as loop controls. Using brother
frankus' example :
$_='axxbcaxbagaxbacba';
foreach my $a (m/a(.*?)b/g) {
print "$a\n";
}
OK, so, from
perlman :
The foreach modifier is an iterator: For each value in EXPR, it aliases $_ to the value and executes the statement
So, right away, we see that foreach doesn't care about, or understand $1 and company at all. It only knows about its control variable ($a, in this case) and its list : (m/a(.*?)b/g).
So what's the for statement's list? It's generated from m/a(.*?)b/g. And, as
perlop states,
(m//) ... in a list context returns a list consisting of the subexpressions matched by the parentheses in the pattern, i.e., ($1, $2, $3...)
So, with this regexp, you get an anonymous list of 4 elements. It's like writing
foreach my $a ($1, $2, $3, $4) {
by the time the code in the loop's running, the regexp has run and returned a list of values that foreach will process.
I hope that makes things a little clearer, this gave me trouble for a while, and hopefully this explanation will minimize the trouble it gives you.
update see below... sometimes convenient variables aren't good for practical use.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.