Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: Read (sysread) binary data into utf8 string

by shmem (Chancellor)
on Apr 03, 2017 at 23:38 UTC ( #1186924=note: print w/replies, xml ) Need Help??

in reply to Read (sysread) binary data into utf8 string


shmem [qurx] ~ > perl -CO use Encode qw/ _utf8_on /; use Devel::Peek; $s = " "; _utf8_on( $s ); substr $s, 0, 1, "\x{b5}"; Dump $s; print length $s, $/; print "\$s: '$s'\n"; __END__ SV = PVMG(0xf64ff0) at 0xedd8c8 REFCNT = 1 FLAGS = (SMG,POK,pPOK,UTF8) IV = 0 NV = 0 PV = 0xee2620 "\302\265"\0 [UTF8 "\x{b5}"] CUR = 2 LEN = 10 MAGIC = 0xf66010 MG_VIRTUAL = &PL_vtbl_utf8 MG_TYPE = PERL_MAGIC_utf8(w) MG_LEN = -1 1 $s: ''

So this has nothing to do with IO layers; sysread apparently does substr, which just does the right thing. Magic.

"\x{b5}" is an iso-8859-1 (a.k.a) latin1 char and a valid UTF8 codepoint, whose UTF-8 hex value is 0xC2B5 (0302 0265 as octal) - MICRO SIGN ().

print chr hex 'b5' eq "\x{00b5}"; __END__ 1

Your file handle was set to raw, so bytes are read. Since perl places the byte into an UTF-8 string slot, it converts it from the internal representation into UTF8 and happily places its char hex value (2 bytes) into the PV slot, to satisfy the utf8-ness.

Similar to what happens here (reversed):

use Encode qw( from_to _utf8_on ); use Devel::Peek; $s = "\x{b5}"; Dump $s; from_to($s, 'latin1', 'utf8'); _utf8_on $s; Dump $s; __END__ SV = PV(0x234fa90) at 0x2375870 REFCNT = 1 FLAGS = (POK,IsCOW,pPOK) PV = 0x2372400 "\265"\0 CUR = 1 LEN = 10 COW_REFCNT = 2 SV = PV(0x234fa90) at 0x2375870 REFCNT = 1 FLAGS = (POK,pPOK,UTF8) PV = 0x249b2c0 "\302\265"\0 [UTF8 "\x{b5}"] CUR = 2 LEN = 10

Except that the 'magic' bits are missing (since none involved).

perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1186924]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2021-06-24 18:38 GMT
Find Nodes?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)

    Results (130 votes). Check out past polls.