How to convert hex to char string in perl

2020-06-29 07:45发布

问题:

I need change the %xx HEX characters to chars. I am trying with this code but it does not works:

#!/usr/bin/perl -w

my $cadena = "%40%61%62";
print $cadena."\n";
$cadena =~ s/%//g;
print "cad: ".$cadena."\n";
my $string =~ s/([a-fA-F0-9][a-fA-F0-9])/chr(hex($1))/eg;
print "traducida: ".$string;

回答1:

Change

my $string =~ s/([a-fA-F0-9][a-fA-F0-9])/chr(hex($1))/eg;

to

$cadena =~ s/([a-fA-F0-9][a-fA-F0-9])/chr(hex($1))/eg;

so that search and replace is done on $cadena.

Output: @ab

40 => @
61 => a
62 => b


回答2:

A better regex pattern:

$cadena =~ s/([[:xdigit:]]{2})/chr(hex($1))/eg;

Use the POSIX character set [:xdigit:] to match a single hexadecimal character and use {2} to specify two and only two of them.



标签: perl char hex