2013-05-09 19 views
7

Qual è un buon modo per creare una stringa perl con il set di flag UTF8 ma contiene una sequenza di byte UTF8 non valida?Creare una stringa perl UTF8 non valida?

C'è un modo per impostare il flag UTF8 su una stringa perl senza eseguire la codifica nativa alla traduzione UTF-X (ad esempio, che accade quando si chiama utf8::upgrade)?

Ho bisogno di fare questo per rintracciare un possibile errore nel driver DBI.

+0

Unicode e Perl come Bonnie e Clyde - ti hanno rubato il tempo e ti hanno concesso una fantastica serata e notte :) – gaussblurinc

risposta

7

Questo è esattamente ciò che Encode di _utf8_on fa.

use Encode qw(_utf8_on); 

my $s = "abc\xC0def"; # String to use as raw buffer content. 
utf8::downgrade($s); # Make sure each char is stored as a byte. 
_utf8_on($s);   # Set UTF8 flag. 

(Non usare mai _utf8_on tranne quando si desidera generare un cattivo scalare.)

È possibile visualizzare il danno utilizzando

use Devel::Peek qw(Dump); 
Dump($s); 

uscita:

SV = PV(0x24899c) at 0x4a9294 
    REFCNT = 1 
    FLAGS = (PADMY,POK,pPOK,UTF8) 
    PV = 0x24ab04 "abc\300def"\0Malformed UTF-8 character (unexpected non-continuation byte 0x64, immediately after start byte 0xc0) in subroutine entry at script.pl line 9. 
[UTF8 "abc\x{0}ef"] 
    CUR = 7 
    LEN = 12 
8

È possibile impostare una sequenza arbitraria di byte con il flag UTF8 ancora impostato mediante l'hacking nel budello di una stringa.

use Inline C; 
use Devel::Peek; 
utf8::upgrade($str = ""); 
Dump($str); 
twiddle($str, "\x{BD}\x{BE}\x{BF}\x{C0}\x{C1}\x{C2}"); 
Dump($str); 
__DATA__ 
__C__ 
/** append arbitrary bytes to a Perl scalar **/ 
void twiddle(SV *s, const char *t) 
{ 
    sv_catpv(s, t); 
} 

uscita tipico:

SV = PV(0x80029bb0) at 0x80072008 
    REFCNT = 1 
    FLAGS = (POK,pPOK,UTF8) 
    PV = 0x80155098 ""\0 [UTF8 ""] 
    CUR = 0 
    LEN = 12 
SV = PV(0x80029bb0) at 0x80072008 
    REFCNT = 1 
    FLAGS = (POK,pPOK,UTF8) 
    PV = 0x80155098 "\275\276\277\300\301\302"\0Malformed UTF-8 character (unexpected continuation byte 0xbd, with no preceding start byte) in subroutine entry at ./invalidUTF.pl line 6. 
Malformed UTF-8 character (unexpected continuation byte 0xbe, with no preceding start byte) in subroutine entry at ./invalidUTF.pl line 6. 
Malformed UTF-8 character (unexpected continuation byte 0xbf, with no preceding start byte) in subroutine entry at ./invalidUTF.pl line 6. 
Malformed UTF-8 character (unexpected non-continuation byte 0xc1, immediately after start byte 0xc0) in subroutine entry at ./invalidUTF.pl line 6. 
Malformed UTF-8 character (unexpected non-continuation byte 0x00, immediately after start byte 0xc2) in subroutine entry at ./invalidUTF.pl line 6. 
[UTF8 "\x{0}\x{0}\x{0}\x{0}\x{0}"] 
    CUR = 6 
    LEN = 12 
Problemi correlati