Hmm I see what you mean, extending the code with more matches soon gets really unwieldy. You need some kind of looping construct.
Now I wish I could say you could handle this easily with a single pattern, but unfortunately, a repetition modifier around captures doesn't produce the desired results:
$_ = 'de ad be ef #junk';
/^(\w\w)(?: (\w\w))*/;
will only retain two captures: in the end, $1 will be 'de', the first capture, and $2 will be 'ef', the last one — the rest will simple have been forgotten about.
There's no way around it, this requires a two step approach: Step 1) extract the whole of all the captures, Step 2), split it into parts.
- The first approach is to use split for step 2:
$_ = 'de ad be ef #junk';
/^(\w\w(?: \w\w)*)/;
my @capture = split ' ', $1;
- Use //g, either in a loop, or in list context.
- //g in list context:
$_ = 'de ad be ef #junk';
my @capture = /\G(?:^|\ )(\w\w)/g;
- A loop with //g in scalar context:
$_ = 'de ad be ef #junk';
my @capture;
while(/\G(?:^|\ )(\w\w)/g) {
push @capture, $1;
}
Be extremely careful with the latter that you don't accidently cause an endless loop. I did, with
/(?:^|\G\ )(\w\w)/g
I'm still not sure why.
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.