Reputation: 293
Why doesn't this sample code work correctly?
#/usr/bin/perl
$a = "aaa%29";
$a =~ s/%/\\x/g;
print "a $a \n";
$b = "aaa\x29";
print "b $b \n";
$c = sprintf($a);
print "c $c \n";
I want to get three times the same output line.
Upvotes: 0
Views: 187
Reputation: 385809
'"','\','x','2','9','"' is Perl code for a string literal that creates a one-character string.
'\','x','2','9' is a different sequence, and it's never passed to the Perl parser, much less executed. Furthermore, sprintf
doesn't treat "\" specially. All the escapes it knows start with "%".
That's why you're not getting the same output.
Upvotes: 1
Reputation: 206699
For the first regexp, you could use:
$a = "aaa%29";
$a =~ s/%([0-9A-F]{2})/chr(hex($1))/gie;
print "a $a \n";
I have no idea what you are trying to do with sprintf
though.
(Turn on warnings in your code with either use warnings;
or passing -w
as an option to perl
. The sprintf
call is invalid.)
Upvotes: 5
Reputation: 2802
If you're trying to decode URLs, as I guess, you should use the uri_unescape
function from the URI::Escape
module.
Or use something like s{%([0-9A-F]{2})}{chr(hex($1))}egi
.
Upvotes: 5