my $var = "Hello World \x{263a}\cM\x0A This bit is trimmed"; print "\$var is $qesc_to{$var}{30}\n"; # output: $var is "Hello World \x{263A}\r\n..."
I didn't use S::E's printable as it doesn't try to provide valid perl strings, making it less usefull for debugging.
#!/usr/bin/perl -wl use strict; use String::Escape qw(printable qprintable elide); use YAML qw(Dump); use Interpolation ( 'elide:$$->$' => sub { elide($_[0],$_[1]) }, 'esc' => \&esc, 'esc_to:$$->$' => sub { elide(esc($_[0]),$_[1]) }, 'qesc' => sub { '"'.esc(@_).'"' }, 'qesc_to:$$->$' => sub { '"'.elide(esc($_[0]),$_[1]).'"' }, 'uniescape' => \&uniescape, 'yaml' => sub { "\n".Dump($_[0]) }, ); my %escaped = map { eval qq{"\\$_"} => "\\$_" } qw(a t e f b); # perlo +p # String::Escape::printable doesn't always produce valid perl strings sub esc { local $_ = shift; s/([\$"@])/\\$1/g; # interpolators s/([\t\e\f\b\a])/$escaped{$1}/g; # portable escapes s/\r/\\r/g, s/\n/\\n/g if("\r\n" eq "\cM\cJ"); # non-portable s/([^ [:graph:]])/sprintf '\\x{%02X}', ord $1/ge; # \x{} form for +clarity $_ = uniescape($_); return $_; } # From /usr/share/perl/5.8.7/dumpvar.pl sub uniescape { join("", map { $_ > 255 ? sprintf("\\x{%04X}", $_) : chr($_) } unpack("U*", $_[0])); } my $var = "Hello World \x{263a}\cM\x0A This bit is trimmed"; print "\$var is $qesc_to{$var}{30}\n"; # OUTPUT: # $var is "Hello World \x{263A}\r\n..." my $long_str = "Some long, long, long, long string"; my $ugly_str = "Some \f string with\r\n\tnewlines,\b tabs & the like \ +x{263a}\n"; print "long string is $elide{$long_str}{25}"; print "ugly_str is $esc{$ugly_str}"; print "ugly_str is $qesc{$ugly_str}"; print "ugly_str is $esc_to{$ugly_str}{35}"; print "ugly_str is $qesc_to{$ugly_str}{35}"; print "ugly_str is $uniescape{$ugly_str}"; # Bonus recipe: my $ds = [ 1,undef, { b => 3 }]; print "\$ds is $yaml{$ds}"; # OUTPUT: # $ds is # --- # - 1 # - ~ # - b: 3
|
|---|