http://qs321.pair.com?node_id=11115297


in reply to Convert JSON to Perl and back with unicode

I am struggling to make either of Data::Dump or Data::Dumper to print rendered(?) unicode characters rather than those ugly escapes but I can't seem to succeed.

Normally I use:

#!/usr/bin/perl -CSDA use utf8; use Modern::Perl qw{2017}; use Data::Dumper; print STDERR Dumper(\%mydatatoshow) =~ s/\\x\{([0-9a-f]{2,})\}/chr(hex +($1))/ger;

Replies are listed 'Best First'.
Re^2: Convert JSON to Perl and back with unicode
by choroba (Cardinal) on Apr 11, 2020 at 00:00 UTC
    Nice and easy! But, it's prone to Unicode injection:
    #! /usr/bin/perl use warnings; use strict; use Data::Dumper; my %mydatatoshow = ( "\N{GREEK SMALL LETTER ALPHA}" => "\\\N{GREEK SMALL LETTER BETA}", '\\x{3b1}' => '\\\\x{3b2}', ); binmode STDERR, ':encoding(UTF-8)'; print STDERR Dumper(\%mydatatoshow); print STDERR Dumper(\%mydatatoshow) =~ s/\\x\{([0-9a-f]{2,})\}/chr(hex +($1))/ger;

    Update: Possibly fixable by

    s/((\\+)x\{([0-9a-f]{2,})\})/ (length($2) % 2) ? substr($2, 1) . chr hex $3 : $1/ger;

    Verified by

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]