How can I use single-line Perl to decode an ASCII string encoded in hexadecimal?

I'd like to write single-line Perl to decode a string of ASCII characters encoded as hexadecimal numbers (for example, the string 48 54 54 50should be decoded as HTTP). I came up with this:

perl -nE 'say map(chr, map { qq/0x$_/ } split)'

It prints an empty line. What am I doing wrong and how do you write it?

+5
source share
4 answers

This is your trick qq/0x$_/that doesn't work. chrexpects a number as an argument, but receives a string literal "0x48". Use a function hexto convert 48to decimal, such as a datageist in its answer .

:

echo '48 54 54 50' | perl -nE 'say map(chr, map { hex } split)'
+6

:

echo '48 54 54 50' | perl -nE 'say map{chr(hex)} split'

, STDIN.

+6

Perl TIMTOWTDI.

, , , . perldoc perlrun, .


. , .

echo '48 54 54 50' | perl -0x20 -pe'$_=chr hex$_'
echo '48 54 54 50' | perl -0x20 -ne'print chr hex$_'
echo '48 54 54 50' | perl -0777 -anE'say map chr,map hex,@F'
echo '48 54 54 50' | perl -0777 -anE'say map{chr hex$_}@F'
echo '48 54 54 50' | perl -0apple'$_=chr hex$_' -0x20
echo '48 54 54 50' | perl -apple'$_=join"",map{chr hex}@F'
echo '48 54 54 50' | perl -lanE'say map{chr hex}@F'

, . , , perldoc perlrun.


perl -0x20 -pe'$_=chr hex$_'

. , , , . , , .

# perl -0x20 -pe'$_=chr hex$_'
$/ = " ";  # -0 ( input separator )
while( <> ){
  $_ = chr hex $_;
} continue {
  print $_;
}

perl -0apple'$_=chr hex$_' -0x20

, .

  • -0 , -l . .
  • -p, .
  • -a @F, .

-a -l -p, . , .

echo '48 54 54 50' | perl -0x20 -pe'$_=chr hex$_'
# perl -0apple'$_=chr hex$_' -0x20
$/ = "";  # -0 ( input separator )
$\ = $/;  # -l ( output separator )
$/ = " "; # -0x20 ( input separator )
while( <> ){
  @F = split " ", $_; # -a ( unused )
  $_ = chr hex $_;
} continue {
  print $_;
}

perl -lanE'say map{chr hex}@F'

, , lanE.

  • -l , say.
  • -E -E, say.
# perl -lanE'say map{chr hex}@F'
$\ = $/; # -l ( output separator set to "\n" )
while( <> ){
  @F = split " ", $_; # -a
  say map { chr hex $_ } @F;
}
+6

?

-ple y/0-9A-Fa-f//cd;$_=pack"H*",$_
-ple $_=pack"H*",$_,join"",split
-nE say map chr hex,split
-naE say map chr hex,@F
+3
source

All Articles