Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Silly newb Regex question

Status
Not open for further replies.

symbiotic

Technical User
Jan 17, 2003
28
0
0
GB
Hey all,
I ran into something with regular expressions that I can't figure out how to do. I've looked at the online perl regex docs and the O'reilly Llama.

Lets say you have a string $string. $string contains N number of /xyz/'s. Is there a way to count the number of /xyz/'s that occur in $string? I know this probably doesn't come up a lot, but it would simplify something I'm working on greatly.

Much thanks,
Symbiotic
 
my $count = ($string =~ /(xyz)/g);

should do the trick. The pattern match, uses the modifier /g to return a list of matches. Seeing as the list is evaluated in scalar context (because of $count) it stores the number of elements in the list.

And Bob's you mother's brother ... so to speak :)

Barbie
Leader of Birmingham Perl Mongers
 
Thanks very much, Barbie.

If you don't mind, I have a few further questions.
The list returned from /(xyz)/g is an array, correct?
Does that mean that whenever you load an array into a scalar variable, such as my $count = ($string =~ /(xyz)/g);
the number of indices of the array is returned?

I'm just curious, as that has helpful implications to me.

Thanks,
Symbiotic
 
I quite often use
Code:
my $count = scalar @some_array
rather than
Code:
my $count = 1 + $#some_array
.

PS Barbie: thought I'd see you at the Expo...

"As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs."
--Maurice Wilkes
 
You got it Symbiotic. Calling an array in scalar context returns the number of elements in the array. I like using it when I want a random element from an array. e.g.:
Code:
print $array[int rand(scalar @array)];
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top