regex, number of matches



#!/usr/local/bin/perl -wC

use strict;

my @text;
$text[1] = "xxx xx xxx xxx";
$text[2] = "yyy yyyy yyy yyy yyy";

my ($chars, $words, $lines) = wc(@text);

print "Chars: $chars\n";
print "Words: $words\n";
print "Lines: $lines\n";

sub wc {
my @ret;
for (@_) {
if (defined) {
$ret[0] += length; # chars
$ret[1] += () = /\S+/g; # words
$ret[2] += 1; # lines
}
}
return @ret;
}


What I found hard to get, is the role of the '()' in the wc-words-line:

$ret[1] += () = /\S+/g; # words

After a while, I understood it as an anonymous array that is filled with
the matches, after which its length is used to increase the words-count.


The creating and filling of () seemed like a waste of cpu-cycles, so I
tried to find another way of counting the number of matches.

Destructive variant:

$ret[1] += s/\S+//g; # words

I settled for:

$ret[1] += 1 while /\S+/g; # words

Is there a better/nicer/smarter/directer way to return the number of
matches from a regex?

See also http://dev.perl.org/perl6/rfc/110.html

--
Affijn, Ruud

"Gewoon is een tijger."


.



Relevant Pages