Counting Characters
Anonymous Monk
created: 2006-03-02 15:25:49
Hi, this should be simple but...I need to count the number of characters set in the variable ($summary). My $summary variable takes the first 500 characters from another variable $text. Sometimes $text might be less than 500 characters so I need to count the number of characters that actually end up in the variable $summary. This is how I get the summary variable...
$summary = substr($text, 0, 500);

Thanks.
Re: Counting Characters
created: 2006-03-02 15:43:00

Use [doc://length|length]. Specifically, use length($summary).

In context:

$text = '.'x600;
$summary = substr($text, 0, 500);
print(length($summary), "\n");    # 500

$text = '.'x500;
$summary = substr($text, 0, 500);
print(length($summary), "\n");    # 500

$text = '.'x400;
$summary = substr($text, 0, 500);
print(length($summary), "\n");    # 400
Re^2: Counting Characters
xdg
created: 2006-03-02 16:25:41

As an addendum -- in case it's not clear for the OP or others -- this works because substr used in the way described takes up to as many characters specified (e.g. 500 in this case). If used on a string shorter than the maximum length, there is no padding added at the end. Thus length works on the summary exactly as one would expect.

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Re: Counting Characters
created: 2006-03-02 16:02:27
print scalar split '', $summary; or if you really want to count the number of characters: map {$count++} split '', $summary; print $count;

Of course none of these is efficient, but if you really do not want to use the built-in length function, ...

CountZero

"If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re^2: Counting Characters
created: 2006-03-02 16:30:38
Don't forget about print $summary =~ y///c;.
Re^2: Counting Characters
created: 2006-03-02 16:59:45

or counting nibbles and dividing by two (bit fraught for multi-byte characters though):

use strict;
use warnings;

my $text = '.'x400;
my $summary = substr($text, 0, 500);
print length(unpack 'H*', $summary) / 2, "\n";

Prints:

400

DWIM is Perl's answer to Gödel
Re: Counting Characters
created: 2006-03-02 23:33:02
Always search first, you'll save yourself time.
A simple search for count characters returns: And length is always the first answer.

MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
** The third rule of perl club is a statement of fact: pod is sexy.

perlmonks.org content © perlmonks.org and Anonymous Monk, antirice, CountZero, GrandFather, ikegami, PodMaster, xdg

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03