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

Well, that's the thing, the string is filled from some external input source and I have no idea what type of data is in it. All I know is how many bytes it contains and how many I need to extract from it. Most likely it will contain arbitrary binary data like a JPEG or tarball, however, it may also contain 8 bit ISO Latin-1 and even Unicode, which means substr() won't work right and will end up extracting entire multi-byte characters instead of just bytes.

  • Comment on Re: Re: How do I safely, portably extract one or more bytes from a string?

Replies are listed 'Best First'.
Re: Re: Re: How do I safely, portably extract one or more bytes from a string?
by liz (Monsignor) on Nov 29, 2003 at 17:43 UTC
    ...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

      Perl will assume bytes

      Don't assume this. :-)

      Perl 5.8.0 will "honor" your TERM environment variable and may use UTF-8 for IO if your terminal is UTF-8.

      For the original problem: Use :bytes when opening the IO channel and treat the content as bytes. If, and only if, you need to work with some Unicode (or UTF-8 or whatever codepage) text convert a substring of it. So the scalar will be marked as containing bytes and substr will work on 8 bit wide characters == bytes. If you let Perl decide if the stream is bytes or UTF-8 it will fail (die/warn/data corruption) if Perl decides for UTF-8 and gets a JPG image...


      Search, Ask, Know