Command line hex dump utility in Perl

This script illustrates block oriented input using sysread in Perl.

I also utilizes the vector flag in the sprintf format string to efficiently convert a string of bytes to their hexadecimal representations.

Please note that while I provide this script in the hopes that it will be useful to you, I make NO GUARANTEES OR WARRANTIES OF ANY KIND. The code is provided subject to the same terms as Perl itself. For more information, please refer to the Perl Artistic License.

#!/usr/bin/perl

use strict;
use warnings;

my $file = shift or die "Usage: hexdump filename\n";

open my $input, '<', $file
    or die "Cannot open '$file' for reading: $!\n";
binmode $input, ':bytes';

use constant CHUNK_SIZE => 4096;
use constant BYTES_PER_LINE => 0x10;

READ_CHUNK:
while ( defined (my $ret = sysread $input, my $buffer, CHUNK_SIZE) ) {
    last READ_CHUNK unless $ret;
    my $pos = 0;
    while ( $pos + BYTES_PER_LINE < $ret ) {
        print hexdump_line(substr $buffer, $pos, BYTES_PER_LINE), "\n";
        $pos += BYTES_PER_LINE;
    }
}

sub hexdump_line {
    my ($row) = @_;
    my $output = sprintf '%*v02X', ' ', $row;
    $row =~ s/[^\x20-\x7e]/\./g;
    $output .= (q{ }) x 4 . $row;
}
__END__