...I have no idea what type of data is in it...

Then how do you think Perl can know (conclusively) what encoding it is in? You need to tell Perl when opening a file (either directly or implicitely with the open pragma), that the contents of that file has a special encoding. From perldoc -f open:

You may use the three-argument form of open to specify IO "lay- ers" (sometimes also referred to as "disciplines") to be applied to the handle that affect how the input and output are processed (see open and PerlIO for more details). For example
                 open(FH, "<:utf8", "file")
will open the UTF-8 encoded file containing Unicode characters, see perluniintro. (Note that if layers are specified in the three-arg form then default layers set by the "open" pragma are ignored.)

Only then will Perl do conversions to turn it into UTF-8 internally and mark the data internally as UTF-8 (which will cause the character semantics to be applied to that data, rather than byte semantics). If you don't tell with which encoding the file should be read, Perl will assume bytes and substr() will work as expected.

Hope this helps.

Liz


In reply to Re: Re: Re: How do I safely, portably extract one or more bytes from a string? by liz
in thread How do I safely, portably extract one or more bytes from a string? by Anonymous Monk

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.