use strict; use warnings; my $string = "non-printable or ill-behaved characters: \x0d \x0a \x00 \b \a"; # my $string = ''; print hexdump(\$string); sub hexdump { my $str = ref $_[0] ? ${$_[0]} : $_[0]; return "[ZERO-LENGTH STRING]\n" unless length $str; # split input up into 16-byte chunks: my @chunks = $str =~ /([\0-\377]{1,16})/g; # format and print: my @print; for (@chunks) { my $hex = unpack "H*", $_; tr/ -~/./c; # mask non-print chars $hex =~ s/(..)(?!$)/$1 /g; # insert spaces in hex # make sure our hex output has the correct length $hex .= ' ' x ( length($hex) < 48 ? 48 - length($hex) : 0 ); push @print, "$hex $_\n"; } wantarray ? @print : join '', @print; } __END__ prints: 6e 6f 6e 2d 70 72 69 6e 74 61 62 6c 65 20 6f 72 non-printable or 20 69 6c 6c 2d 62 65 68 61 76 65 64 20 63 68 61 ill-behaved cha 72 61 63 74 65 72 73 3a 20 0d 20 0a 20 00 20 08 racters: . . . . 20 07 .