How to print out the hexadecimal content of one text using Perl binmode?

95 Views Asked by At

Can someone tell me how binmode in Perl can be used to achieve the same function as following one-liner, so as to print out the hex data of one text ?

$ perl -nle 'print map {sprintf "%02X",ord} split //'

For example, if I input "abcABC", the output will be "616263414243".

Please give a similar one-liner using binmode.

Thanks.

3

There are 3 best solutions below

0
On

binmode would be of no use at doing what you asked. There are currently no PerlIO layers that convert all output bytes but 0A to their ASCII hex representation.

0
On

Are you asking how to do that from within a program? The default input mode is the same as binmode on Linux, and on Windows the only difference is that every CR LF is converted to LF.

So you can safely write this.

while (<>) {
    chomp;
    printf '%02X, $_ for split //;
    print "\n";
}

with the proviso that the CR characters will disappear if you are reading a Windows file using a Windows version of perl

0
On

I don't understand your insistance on using binmode, but perhaps this is what you mean?

perl -le 'print map { sprintf q{%02X}, ord } split //, shift' abcABC

output

616263414243