Quote:
Thanks for the reply, I'm not sure I quite understand what you are doing for me to make sense of it.
|
I tried to show You some perl code that can extract the hexadecimal values from your example data as provided in your original post. Did you run or test my code?
Quote:
What I tried doing was opening a file, converting to hex and using substr to pull the location...
|
That didn't make much sense for me. But from the example code You have supplied, I can infer
that you meant to extract some hex digits, as indicated by an offset value (relative to the beginning of the not-yet-encoded bytes read from the input file).
I am getting the Impression that You are learning Perl from some seriously outdated tutorials/documentation. This is hurting You!! Please consider to use the
Book "Modern Perl" by chromatic, which can had for free as a PDF file. Always
use strict; in your perl code (except perhaps for one-liners). Also try to get help from
Perl::Critic.
Okay, back to Your code. I have tried to refactor it into something I could debug, then I have added an alternative code path and some comments explaining what I think Your codes problem is. Please read and run this, both code paths:
Code:
#!/usr/bin/perl
use strict;
use warnings;
use autodie; # Implicit error handling for IO. Optional, makes this script
# simpler yet safer.
my %Class_Table;
my $file_bytes_hex_encoded;
sub read_and_convert_bytes_to_hexadecimal
{
my $input_filename = shift;
my $value;
open my $input, '<', $input_filename or
die "ERROR : Cannot open file $input_filename: $!.\n"
;
{
local $/ = undef; # enable slurp mode to read entire file at once.
$value = <$input>;
# (IO Errors ignored or catched via autodie.)
}
close $input;
$value = unpack( "H*", $value );
return $value;
}
sub extract_hex_digits
{
my( $loc_start, $substr_length ) = @_;
printf "Initial offset into file bytes: $loc_start decimal (0x%x hex)\n",
$loc_start
;
if ( 1 ) { # Change 1 to 0 for old bahavior.
$loc_start = 2 * $loc_start;
# The multiplication by 2 converts from byte offset to
# hex digit pairs offset, which is okay...
}
else {
$loc_start = 2 * hex( $loc_start );
# ... But the "hex" invocation damages the offset! I.e. Decimal 80
# is interpreted as hex 0x80, which has a numeric value of
# decimal 256!
}
printf "New offset into hex encoded file bytes: "
. "$loc_start decimal (0x%x hexadecimal) - Is this intended?!?\n",
$loc_start
;
my $result = substr $file_bytes_hex_encoded, $loc_start, $substr_length;
return $result;
}
$file_bytes_hex_encoded = read_and_convert_bytes_to_hexadecimal( $ARGV[ 0 ] );
my $class = extract_hex_digits( 80, 2 );
$Class_Table{ $class } = "I don't know what is expected here";
print "Class $class = $Class_Table{ $class }\n";
my $level = extract_hex_digits( 72, 2 );
print "level=$level\n";
exit 0;
__END__
If You don't have an input file handy, just use the script itself as input:
perl file_hex_extract.pl file_hex_extract.pl
I hope I understood Your intentions right this time.