Reading a binary file and printing it's contents as hex values
Seems like a trivial task - and it is.
But to get to the point on how to actually achive this with not that much code took myself around two hours.
So for documentation purposes here's a simple yet small routing to accomplish the task:
open my $handle, '<:raw', $file or die qq{opening '$file': $!};
while (defined(my $buffer = <$handle>)) {
printf '%02x ', ord substr $buffer, $_, 1
for 0 .. length($buffer) -1;
print '';
}
close $handle;
The above code opens the file for reading in raw mode. While iterating over the file, it's value is printed byte-per-byte in hexadecimal format.
P.S.: There a lot of more blog posts to come. This is just a small 'quickie' at night.
Thanks for posting. You don't need the "defined" in your while expression, do you? That confused me a bit, until I recalled that when reading file handles, Perl automagically inserts "defined" into the
while( my $buffer = )
construct. Of course, one person's clutter can be another person's clarification.