Regardless of the conventions of your tools, you can be assured of always getting the byte count and only the byte count by turning the utf8 flag off. So if you are uncertain:

#copy so we don't muck utf8 flag on original string my $sTmp=$someData; Encode::_utf8_off($sTmp); my $iLength = length($sTmp);

or for future use you could just wrap this up in a sub:

sub countBytes { my $s=$_[0]; #makes copy Encode::_utf8_off($s); return length($s); } # or to save memory by avoiding a copy for loooong strings # BUT note: may not be a good idea if string is shared by multiple # threads since this is not atomic and another thread could grab # control while the utf8 bit is temporarily off. # The copy approach is more stable and thread friendly. sub countBytes { my $bUtf = Encode::is_utf8($_[0]); Encode::_utf8_off($_[0]); my $i=length($_[0]); Encode::_utf8_on($_[0]) if $bUtf; return $i; } #calc bytes before printf to show flag is indeed preserved my $s=chr(0x160); my $iBytes = countBytes($s); printf "chr=<%s> utf8-flag=%s length=%d bytes=%s\n" , $s, Encode::is_utf8($s)?'yes':'no', length($s), $iBytes; #outputs: chr=<?> utf8-flag=yes length=1 bytes=2

Best of luck with your project.

Update: added memory friendly, thread unfriendly version of countBytes()


In reply to Re^5: Size and anatomy of an HTTP response by ELISHEVA
in thread Size and anatomy of an HTTP response by Discipulus

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.