# # decode_string: display the ascii value of each character of a string # # In: $1 ... the string the decode # $2 ... (optional) number of characters to show per line # $3 ... (optional) a flag: nonzero = hilight non-printing chars # $4 ... (optional) a flag: 0 = show hex, nonzero = show decimal # $5 ... (optional) the symbol representing non-printing chars # # Result: Displays the value of each ascii character in the string, # with a summary of the string length, including number of # printable and non-printable characters. # sub decode_string { my ($str, $nper, $b_hi, $b_dec, $nonasc) = @_; # Defaults $b_dec ||= 0; $nper ||= ($b_dec? 12: 16); $nonasc ||= '.'; $b_hi ||= 0; # Anonoymous subroutines my $pprintable = sub { ($_[0] < 32 || $_[0] > 126)? 0: 1 }; my $pshow_asc = sub { my ($idx, $pchars, $width) = @_; return unless @$pchars; $idx and map { print " " x (3 + $width) } ($idx .. $nper-1); print " ["; map { printf "%s", $pprintable->(ord $_)? $_: $nonasc } @$pchars; print "]"; @$pchars = ( ); }; # Variable initialization my ($pasc, $idx, $ntext, $nnontext) = ([ ], 0, 0, 0); my $hilight = $b_hi? "\e[101m": ""; # Display the string print "-" x 79; my $len = length($str); foreach my $i (0 .. $len-1) { ($i % $nper) or $pshow_asc->($i, $pasc, $b_dec); ($i % $nper) or printf "\n %7d|", $i; push @$pasc, my $char = substr($str, $i, 1); my $hlchar = ""; if ($pprintable->(ord $char)) { ++$ntext; } else { ++$nnontext; $hlchar = $hilight; } printf $b_dec? " $hlchar%3d\e[m": " $hlchar%02x\e[m", ord $char; } # Summary $pshow_asc->($len % $nper, $pasc, $b_dec); print "\n\n String length = $len "; print "($ntext printable, $nnontext non-printable)\n", "-" x 79, "\n"; } #### select(undef, undef, undef, 0.05);