On Jan 12, 2008 12:29 PM, Rob Dixon <[EMAIL PROTECTED]> wrote:
snip
> My best guess at what you're looking for is the total number of bytes in
> all the elements of an array. This can be achieved by manually
> accumulating the lengths:
>
>    use strict;
>    use warnings;
>
>    my @ar = qw(one two three four five);
>
>    $char = 0;
>    $char += length foreach @ar;
>
>    print "char<$char>\n";
>
> which outputs "char<19>".
>
> If you're hoping for something different from this then perhaps you
> would let us know.
snip

It is important to note that this returns the number of characters,
not the number of bytes (in this case they are the same since all of
the UTF-8 characters in your string take up only one byte).  You need
to use the bytes pragma to force length to return the number of bytes:

#!/usr/bin/perl

use strict;
use warnings;

#\x{1816} is the Mongolian digit 6, one character, three bytes
my @ar = (qw(one two three four five), "\x{1816}");

my $char = 0;
$char += length for @ar;

my $bytes = 0;
{
    use bytes;
    $bytes += length for @ar;
}

print "$char characters and $bytes bytes\n";

Of course, all of this just tells of the string length of the values,
not the in-memory size.  For instance,

my $num = 12345;

takes up less room (at least at first) than

my $str = "12345";

because the former is being stored as a number (SvIV) and the later is
being stored as characters (SvPV).  The length function will return
five for both of them.  I believe, but I haven't delved into perlguts
in a long time, that $num will take up more memory than $str after
this operation

my $len = length $num;

because $num will contain both the numeric and character
representations (SvPVIV) so it won't have to generate the character
version again if we ask for it later.  I do not know of a good way to
determine the in-memory size of a scalar value (and consequently array
and hash values).

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to