简体   繁体   中英

printing data as hexdump in perl

I am trying to print data as hexdump in perl but looks like its only working when i am "hard coding" the variable with hex dump value. In below code, hexdump is printed for first case but for second case ($var2), it just prints the data that is read from the file handle

#!/usr/bin/perl
use Data::Dumper;
$var = "\xE9\x92\x97\xAF\xE9\x92\x97\xB5";
print "the first dumper is\n";
print Dumper($var);
my $filename = 'c.txt';
open($fh, "<", $filename);
{
local $/;
$var2 = <$fh>;
chop($var2);
}
close($fh);
$var5 = $var2;
print "the second dumper is\n";
print Dumper($var5);

The output of above code is

[root@abc]# perl code.pl 

the first dumper is

$VAR1 = 'é’—¯é’—µ';

the second dumper is

$VAR1 = '"\\xE9\\x92\\x97\\xAF\\xE9\\x92\\x97\\xB5"';

It looks like perl is appending an extra backslash with every slash present in the filehandle input. How can i print the file handle data as hexdump? The contents of c.txt file are

[root@abc]# cat c.txt 
"\xE9\x92\x97\xAF\xE9\x92\x97\xB5"

Well you can do this

#!/usr/bin/perl
use Data::Dumper;
$var = "\xE9\x92\x97\xAF\xE9\x92\x97\xB5";
print "the first dumper is\n";
print Dumper($var);
my $filename = 'c.txt';
open($fh, "<", $filename);
{
local $/;
$var2 = <$fh>;
chop($var2);
}
close($fh);
$var5 = $var2;
$var5 =~ s/"|\\x//g;
print "the second dumper is\n";
print Dumper(pack("H*",$var5));

I'm using search and replace to remove all the " chars and the \\x as these are just cruft used to help make it human readable. Then pack it as a hex string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM