regex, number of matches
- From: "Dr.Ruud" <rvtol+news@xxxxxxxxxxxx>
- Date: Fri, 23 Sep 2005 19:34:05 +0200
#!/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."
.
- Follow-Ups:
- Re: regex, number of matches
- From: John W. Krahn
- Re: regex, number of matches
- From: John Bokma
- Re: regex, number of matches
- From: Brian Wakem
- Re: regex, number of matches
- Prev by Date: Re: Perl to move files by specific size
- Next by Date: Re: multithreaded web crawler
- Previous by thread: FAQ 9.3 How can I get better error messages from a CGI program?
- Next by thread: Re: regex, number of matches
- Index(es):
Relevant Pages
|