I am new to perl. I am trying to write code that reads data from a binary file, and returns it in a specifique format. it can be either decimal, unsigned, hexadecimal... my binary file when opened in a hex editor looks something like this:
7C 00 48 00 D6 00 E4 07 04 07 14 36 39 00 00 36 00 D6 00 44 CD 08 FF 00 00 00 00 FF 00 00 00 00 FF 00 00 00 00 FF 00 00 00 00 7C 00 48 00 D6 00 E4 07 04 07 14 37 02 00 00 36 00 D6 00 44 CE 07 FF 00 00 00 00 FF 00 00
I know that every 9 bytes in the file represent 1 full unit witch includes 6 variables: start a 1 byte unsigned integer, Devtype 1 byte signed integer, and 4 bytes hexDevUID , year a 2 bytes unsigned integer , month and day each is 1 byte unsigned integer. here is my code which doesnt function correctly:
#!/usr/bin/perl
use feature qw(say);
use strict;
use warnings;
use constant BUFSIZE => 9;
my @input_file;
@input_file = 'path\ZONE0.txt';
open (my $BIN, "<:raw", $input_file[$i]) or die "can't open the file @input_file: $!";
my $buffer;
while (1) {
my $bytes_read = sysread $BIN, $buffer, BUFSIZE;
die "Could not read file @input_file: $!" if !defined $bytes_read;
last if $bytes_read <= 0;
my @decimal= map { unpack "C", $_ } split //, $buffer;
my $start= $decimal[0];
my $DevType = $decimal[1];
my @DevUID =@decimal[5,4,3,2];
my $string_DevUID = join('', $string_DevUID);
my $hexDevUID =sprintf("0x%x",$string_DevUID);
my @year=@decimal[6,7];
my $month=$decimal[8];
my $day = $decimal[9];
say $start;
say $DevType;
say $hexDevUID;
say @year;
say $month;
say $day;
}
my idea was to read the 9 bytes at a time and then treat the variables separately, but I am sure I am losing the correct values in between the split and unpack. I am able to get some data but the values are not correct they dont match to what my hex editor shows. I have also tried reading one byte at a time and joining values for the variables with more than 1 byte but I still somehow mess up the values, Any ideas on what I am doing wrong?
update: I guess split returns an array of characters and Formats might be lost in that step but I dont know of an other way to get an array out of $buffer. My code generates this error if (as suggested below) I try to unpack the buffer directly without the split. :
Use of uninitialized value in join or string