Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

simple hexdump

by moxliukas (Curate)
on Jun 11, 2002 at 13:14 UTC ( [id://173460]=perlcraft: print w/replies, xml ) Need Help??

   1: <code>
   2: # This is a simple script that dumps a hexadecimal 
   3: # representation of a file
   4: # It was origginally written in C, so it suffers from some 
   5: # C syntax (mostly `for' loops could probably be redone
   6: # in a more `perlish' way and the use of ternary operator 
   7: # ?: is quite ugly). It also overuses printf's where a more 
   8: # elegant solution with `unpack' could be found.
   9: # Never-the-less, it did the job that I needed to do, so
  10: # here it is for all to see (and maybe even use). 
  11: 
  12: use strict;
  13: use warnings;
  14: $#ARGV == 0 or die 'Usage: hexdump.pl file';
  15: open my $inpt, "<$ARGV[0]" or die "Can't open $ARGV[0]";
  16: binmode $inpt;  # for DOS and the rest...
  17: for(my $line_no = 0; my $i = read $inpt, $_, 16; $line_no++)
  18: {
  19:   push my @a, split //;  # put things onto char array
  20:   printf "%05x ", $line_no;  # print line number 
  21:   # print hex codes
  22:   printf "%02x ", ord() & 0xff foreach @a;  
  23:   # pad last line if neccessary
  24:   for(my $j = $#a; $j < 15; $j++) { print '   '; }   
  25:   # if a character is a control character, print a dot, 
  26:   # else print normal ascii char
  27:   (ord() < 32 or ord() == 127) ? print "." : print foreach @a;  
  28:   print "\n";
  29: }
  30: close $inpt;
  31: </code>

Replies are listed 'Best First'.
Re: simple hexdump
by Anonymous Monk on Jun 12, 2002 at 00:32 UTC
    Here's another: a bit cleaner and about 30% faster.
    #!/usr/bin/perl -w use strict; $/ = \16; my $line_no = 0; binmode ARGV; while(<>){ my @hex = map{sprintf "%02x",ord($_) & 0xff} split//; push @hex, (' ') x (16 - @hex); tr/\000-\040\177/./; printf "%05x %s %s\n", $line_no++, "@hex", $_; }
Re: simple hexdump
by Mr. Muskrat (Canon) on Jun 11, 2002 at 23:00 UTC

    ++moxliukas

    Very nice. However, was it your intention for it to print out "Usage: hexdump.pl file at /filepath/hexdump.pl line 13." when the user does not give a filename? If not then, I'd use this instead:
    $#ARGV == 0 or die "Usage: hexdump.pl file\n";
    That changes the output to simply "Usage: hexdump.pl file".


    Who says that programmers can't work in the Marketing Department?
    Or is that who says that Marketing people can't program?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-04-25 21:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found