[EMAIL PROTECTED] wrote:
How do we get the length of a variable in bytes?
I see the length function returns length in characters. unless you (From perldoc -f length):
           use "do { use bytes; length(EXPR) }"

Nothing there would seem to indicate it cannot be used to get the
length in characters or bytes of an array.

Yes. length() works on a scalar value, and returns the length of that
value in terms of unicode characters, unless forced to use bytes instead
as you have shown.

It does say:
   . . . . . . . . . . . . . . . . . Note that this cannot be
   used on an entire array or hash to find out how many elements
   these have.  For that, use "scalar @array" and "scalar keys
   %hash" respectively.

An array or hash in scalar context evaluates to its element count. So

  my $length = @array;

will also work.

But that doesn't appear to preclude using it to get the length in
characters.  But apparently you cannot since this returns <1>.
  my @ar = ("one,","two","three","four","five");
  my $char = length @ar;
  print "char<$char>\n"
char<1>

Now we reach murky waters in that you are trying to establish the
'length' of an array, which is meaningless until you define it. What
your code does is to take the number of elements in @ar (length forces a
scalar context on its parameter) and return the length in characters of
that value. So

  my $char = length @ar;

is evaluated as

  my $char = length 5;

which gives $char the value 1 since '5' is one character long.

There is a reference right at the end that might be pointing at what I'm
looking for but I can't understand what it means:

. . . . . . . . . . . . . . . . . . . . . . . .To get the length in bytes, use "do { use bytes; length(EXPR) }", see
  bytes.

What is meant by `see bytes'?  Since it appears in function
documentation it seems to indicate there is a function called `bytes'
or at least something in the FAQ.

'bytes' is a pragma, and documentation on it can be retrieved in the
same way as for all pragma and modules by issuing

  perldoc bytes

But here, neither `perldoc -f' bytes nor `peldoc -q bytes' shows
anything.

No. Because it is not a function and doesn't appear in the title of any
FAQ.

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.

HTH,

Rob


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


Reply via email to