length 
length EXPR
lengthThis function returns the length in codepoints
(programmer‐visible characters) of the scalar value
EXPR. If EXPR is
omitted, it returns the length of $_.
(But be careful that the next thing doesn’t look like the start of an
EXPR, or Perl’s lexer will get confused. For
example, length < 10 won’t
compile. When in doubt, use parentheses.)
Do not try to use length to
find the size of an array or hash. Use scalar
@array for the size of an array, and scalar keys %hash for the number of key/value
pairs in a hash. (The scalar is
typically omitted when redundant.)
To find the number of graphemes (user‐visible characters) in a string, either count them:
my $count = 0; $count++ while our $string =~ /\X/g;
or use the CPAN Unicode::GCString module, which lets you work with a string as a sequence
of graphemes instead of as a sequence of codepoints. That module also
tells you how long a string is in print columns. That way you can still
use printf justification and, if
you’re creative, maybe even format
and write, even though some
codepoints occupy 0 columns, others 1 column, and still others 2 columns
when printed.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access