in reply to Re: 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?

...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

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

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