Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

String Escaping recipe for Interpolation

by bsb (Priest)
on Jan 15, 2006 at 12:39 UTC ( [id://523327]=CUFP: print w/replies, xml ) Need Help??

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..."

Interpolation uses tied hashes to transform data before interpolating it into a string. Here is a snippet to display an escaped version, possibly smart truncated with String::Escape's elide.

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://523327]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-03-29 11:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found