note
jeffa
First off [Nik], please start using code tags and making
your posts look nice in general. When you post something
to this site, you are suppose to click the PREVIEW button
first - don't click SUBMIT until the posts looks good. How
do you make a post look good? By using our [id://29281]
and reading over [id://17558] first. I have looked at your
previous posts and see that you have never learned this
simple, important step for getting good information and
respect from this community.
<p>
If you want to understand the code you have been given,
please try to do a little research on your own. A good
<tt>perldoc</tt> page to read is [perldoc://perlre], this
contains every answer to all of your regex questions.
</p>
<p>
What is hard to understand, however, is this:
<code>
$count = () = $data =~ m/and/g;
</code>
so let's break it down. Hopefully, you realize
that <code>$data =~ m/and/</code> is a boolean test. It
just asks <i>"does $data contain the word 'and'?"</i>. If it
does, then the answer to the question is true. If it does
not, then the answer to the question is false. However, we
don't want to know if 'and' appears or not, we want to count
how many times it does appear.
<p>
Hopefully you also know about the 'g' modifier. This allows
us to match the pattern more than once. Of course, in our
simple version above, 'g' is not needed because we only
ask if 'and' appears or not - the number of times is
irrelevant.
</p>
This finally brings us to "scalar context" versus
"list context" (see [perldoc://perldata]). As you
found out in your original question, this does not work:
<code>
$count = $data =~ m/and/g;
</code>
Because we ask the question in "scalar context", we get back
... true (assuming $data does contain 'and'). In order to
actually count the occurances, we have to explicitly tell
Perl that we want "list context". This is why we have the
bare parens (an empty list) in between $count and $data.
If you still don't understand, don't worry -- this took me
a few months to understand. :)
<p>
The rest of your questions are all addressed in
[perldoc://perlre]. I would answer them now, but since you
didn't use code tags ... i will instead instruct you to go
do some reading. And next time, please for the love of God
use code tags man.
</p>
Oh, and as for Python versus Perl ... what do you think we
are going to say? This is a Perl site! :P
<p>jeffa</p>
<font size=1>
<pre>
L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(<a href="http://jeffa.perlmonk.org/tripdid.mp3">the triplet paradiddle with high-hat</a>)
</pre></font>
292854
292859