In a manner of thinking, Perl has two kinds of strings: strings of characters and strings of bytes. It seems your len function expects to be working on strings of bytes, yet you have a string of characters (since 0x03C5 is outside the range of bytes). Why don't your convert your string of characters into a string of bytes?

Converting from strings to bytes is known as "encoding", and Encode is the module to do it. The question you have to answer is: Which encoding to you wish to use? You could, for example, encode using utf8:

$octets = encode("utf8", $string);
In context, we get:
use Encode qw( encode ); sub string_to_literal { local $_ = @_ ? $_[0] : $_; s/(.)/ my $o = ord($1); if ($1 eq '"' ) { '\\"' } elsif ($1 eq '\\' ) { '\\\\' } elsif ($1 < 0x20 || $1 >= 0x7F) { sprintf('\\x{%X}', $o) } else { $1 } /eg; return qq{"$_"}; } sub octet_dump { return join ' ', map { sprintf('%02X', ord($_)) } map /(.)/g, @_ ? $_[0] : $_; } $string = "\x{03c5}"; print("\$string is ", length($string), " chars long: "); print(string_to_literal($string), "\n"); $octets = encode("utf8", $string); print("\$octets is ", length($octets), " bytes long: "); print(octet_dump($octets), "\n");

outputs

$string is 1 chars long: "\x{3C5}" $octets is 2 bytes long: CF 85

Both $string and $octects contains "υ", except the character is in Perl's internal character format in $string and in utf8 in $octects.


In reply to Re: impose 'use bytes' on another package by ikegami
in thread impose 'use bytes' on another package by saintmike

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.