Just a Little Program... to be sure. · Mar 3, 11:38 PM by Dylan Doxey
Some things are just obviously correct and you go about your business doing things the correct way until one day you realize there's a better way.
For example, you're going about your business, about to populate an array with regex matches and you might wonder, "Does it really need to be done in a loop?"
1 #!/usr/bin/perl -Tw
2
3 use strict;
4 use warnings;
5 use Data::Dumper;
6
7 my $text = "
8 abc123abc
9 abc123abc
10 abc123abc
11 abc123abc
12 ";
13
14 my $regex = qr{ ( \d+ ) }xms;
15
16 {
17 my @matches = $text =~ $regex;
18
19 print 'A: ' . Dumper( \@matches ) . "\n";
20 }
21 {
22 my @matches = $text =~ m/$regex/g;
23
24 print 'B: ' . Dumper( \@matches ) . "\n";
25 }
26 {
27 my @matches;
28 while ( $text =~ m/$regex/g ) {
29
30 push @matches, $1;
31 }
32
33 print 'C: ' . Dumper( \@matches ) . "\n";
34 }
If you're still reading, then it's probably not obvious to you... as it now is to me.
Long story short, here's what you get:
1 A: $VAR1 = [ 2 '123' 3 ]; 4 5 B: $VAR1 = [ 6 '123', 7 '123', 8 '123', 9 '123' 10 ]; 11 12 C: $VAR1 = [ 13 '123', 14 '123', 15 '123', 16 '123' 17 ];
Happy computing.

Commenting is closed for this article.
Permutations SCP -- The World's Most Convenient File Transfer
