Category: Utility Code
Author/Contact Info aepage@users.sourceforge.net
Description: A quick hex dumper that is very small and very handy for debugging packs/unpacks and vecs.
print hd("hello world\n"), "\n" ; 0000 68 65 6C 6C 6F 20 77 6F hello wo 0008 72 6C 64 0A rld.
package HexDump ;

=pod

=head1 Synopsis  

   Quick program to convert strings into 'dumps' of their hex values. 
+ Useful for debugging
   pack, unpack and vec usages.  

   use HexDump ;
   my($hexDump) = hd("Hello World") ;

=head1 Example:


my $str = "Hello World\n" ;

print "$str", HexDump::hd($str), "\n" ;

=cut

require Exporter;

our @ISA = qw(Exporter);

use vars qw/@EXPORT/ ;

@EXPORT = qw/hd/ ;

my($hdWidth) = int($ENV{HEXDUMP_WIDTH}) || 8 ;

##
## converts non printable chars to '.' for a string
##
sub printablestr {
    return join "", map { (ord($_) >= 32 && ord($_) < 127) ? $_ : '.' 
+} split //, $_[0] ;
}

##
## hex dump utility function
##
sub hd {
    my(@retList) ;
    my($width) = $hdWidth ;
    my($offset) = 0 ;
    my($len, $fmt, $n, @elems) ;

    for( @_ ) {
    my($str) ;
    $len = length $_ ;
    
    while($len) {
        $n = $len >= $width ? $width : $len ;

        $fmt = "\n%04X  " . ("%02X " x $n ) . ( '   ' x ($width - $n) 
+) . " %s" ;
        @elems = map ord, split //, (substr $_, $offset, $n) ;
        $str .= sprintf($fmt, $offset, @elems, printablestr(substr $_,
+ $offset, $n)) ;
        $offset += $width ;

        $len -= $n ;
    } # while

    push @retList, $str ;
    } # for

    return $retList[0] unless wantarray ;
    return @retList ;
} # end of hd

1 ;
Replies are listed 'Best First'.
Re: HexDump.pm
by DrHyde (Prior) on Oct 16, 2003 at 07:41 UTC
Re: HexDump.pm
by belg4mit (Prior) on Oct 16, 2003 at 02:24 UTC
    ## convert non printable chars to '.' for a string sub printablestr { my $str = shift; $str =~ s/[^\x20-\x7f]/./g; return $str; } ## hex dump utility function sub hd { my(@retList, $len, $width, $i, $str); $width = $ENV{HEXDUMP_WIDTH} || 16; $i = 0; $str = ''; foreach( @_ ) { while( my $str = substr($_, $width*$i, $width) ){ $len = length($str); push @retList, sprintf("%04X ".('%02X ' x $len ).(' 'x($width - $len))." +%s\n", $width*$i++, map({ord} split//, $str), printablestr($s +tr)); last if $len < $width; } } return $retList[0] unless wantarray; return @retList; }

    --
    I'm not belgian but I play one on TV.