Others already pointed out the
scalar context trick.
There are also
non-destructive methods available to count the occurence of
a certain character. You can find this in
perlop as well.
Depending on what you need exactly, you can use different
solutions:
$txt = "This is a string";
$count = $txt =~ tr/ //; #counts all spaces
$count = () = $txt =~ m/\s/g; #counts all whitespace characters
$count = () = $txt =~ m/\s+/g; #counts whitespace occurences (default
+ [split] behavior)
It's probably a good idea to check out
7 Stages of Regex Users as well.
Oh yeah, Don't be confused by the
=~. It's not
only an assignment, it's also a function that returns something,
just like when it acts on $_. See
perldoc, illustrated by:
$count = tr/ // for ($txt);
Does exactly the same, but now
the match is done on $_. $_ is assigned to by
for. Don't
assign to $_ yourself (or use
local). A complete different
approach still is the use of
index, which may be handy
under certain circumstances.
Hope this helps,
Jeroen
"We are not alone"(FZ)
Update: I must have been sleeping.... read merlyn's
reply... code is working now.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.