i'd like to know how to get the number of regexp matches a pattern returns
ex: if I have $_ = "fooFOObarBAR";$_ =~ /[a-z]/
it would return 6



8 Years
Discussion Span
Last Post by KevinADC

But you have to remove the second $_, that is resetting the value.

$_ = "fooFOObarBAR";
print "$count @var\n";

Try not to back to back post... it's bad etiquette (though sometimes necessary). The better alternative is to edit your post within the grace-period provided by the site.


OK, will do. Sorry. I am new to these forums, but not new to perl. I will edit in the future. My bad.


An interesting construct to do the same thing. No need to actually use a named array:

$_ = "fooFOObarBAR";
print "$count\n";

But I would do it like this myself:

$_ = "fooFOObarBAR";
$count = tr/a-z/a-z/;
print "$count\n";

Well, I would normally have left the named array off and just done it with a simple scalar, but since the questioner is a newbie to perl, I wanted to show where the values end up when you use () and when you use just a scalar. I read a funny article in perl journal years ago (it was satire) in which the guy was supposedly using perl for military technology and forgot the () in the tolerances, so he was getting a "1" because it was the count of matches, rather than the value of matches.


Cool. Its sort of moot anyway in this example since tr/// is really the better way to do it since it involves no pattern matching, just simple character recognition.

I just thought the construct was interesting:

$count = () = /[a-z]/g;

I remember the first time I saw that years ago and it was a bit of a revelation in how perl works.


Yeah, I find that interesting as well. Perl is amazing - thanks Larry!

I told a co-worker that I use perl everyday and he said "I hate that language" so I immediately lost all respect for him (haha).

You're right tr/// is better and more efficient. I sometimes use some old tricks because I have never had anyone actually teach me perl, just figured out by doing. I am now writing (most) everything object oriented in perl - which I hadn't before because I wrote most stuff very C-like.


Well, we are in the same boat, I never learned perl formally either. Last time i was in school I was learning how to write programs on punch cards. Which totally turned me off to programming for a very long time. ;)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.