That code (unpack 'W' specifically) only works in 5.10. Below is a version that works in 5.8+ (when unicode support was added), and a reverse function for 5.8+ that safe for use on untrusted strings.
sub escape_5_10 { join '', map { $_ > 255 ? sprintf('\\x{%04X}', $_) : chr() =~ /[[:cntrl:]]/ ? sprintf('\\x%02X', $_) : quotemeta(chr()) } unpack('W*', @_ ? $_[0] : $_) } sub escape { join '', map { ord() > 255 ? sprintf('\\x{%04X}', ord()) : /[[:cntrl:]]/ ? sprintf('\\x%02X', ord()) : quotemeta() } map /./gs, @_ ? $_[0] : $_ } sub unescape { my $s = @_ ? $_[0] : $_; $s =~ s/ \G (?: \\x \{ ([0-9a-fA-F]+) \} | \\x ([0-9a-fA-F]{1,2}) | \\(.) | # No escapes ) ([^\\]*) / ( defined($1) ? chr(hex($1)) : defined($2) ? chr(hex($2)) : defined($3) ? $3 : '' ) . $4 /xesg; $s } # XXX Assumes. Good enough. Avoids warn. binmode STDOUT, ':encoding(UTF-8)'; my $s = '<3' # \W and \w . chr(0x04D2) # wide char . "\cC"; # ctrl char print("$s\n"); $s = escape($s); print("$s\n"); $s = unescape($s); print("$s\n");

Update: Functions now default to using $_ is no arg was supplied.


In reply to Re: Escaping Wide Characters by ikegami
in thread Escaping Wide Characters by mobiusinversion

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.