Thanks to everyone in advance.
I'd like to access the nth byte of a binary scalar. For example you could get all the file data in one scalar variable...
Imagine that the binary data is collected into scalar...
open(SOURCE, "<", "wl.jpg");
my $thisByteData = undef;
while(<SOURCE>){$thisByteData .= $_;}
close SOURCE;
$thisByteData is raw binary data. When I use length($thisByteData) I get the byte count back, so Perl does know how big it is. My question is how can I access the Nth byte?
Side note: My function is going to receive this binary scalar, its in my function that I want to access the Nth byte. The help regarding how to collect this data is appreciated but not what I'm looking for. Whichever way the other programmer wants to collect the binary data is up to them, my job is to get the Nth byte when its passed to me :)
Again thanks so much for the help to all!
Thanks to @muteW who has gotten me further than ever. I guess I'm not understanding unpack(...) correctly.
print(unpack("N1", $thisByteData));
print(unpack("x N1", $thisByteData));
print(unpack("x0 N1", $thisByteData));
Is returning the following:
4292411360
3640647680
4292411360
I would assume those 3 lines would all access the same (first) byte. Using no "x" just an "x" and "x$pos" is giving unexpected results.
I also tried this...
print(unpack("x0 N1", $thisByteData));
print(unpack("x1 N1", $thisByteData));
print(unpack("x2 N1", $thisByteData));
Which returns... the same thing as the last test...
4292411360
3640647680
4292411360
I'm definatly missing something about how unpack works.
If I do this...
print(oct("0x". unpack("x0 H2", $thisByteData)));
print(oct("0x". unpack("x1 H2", $thisByteData)));
print(oct("0x". unpack("x2 H2", $thisByteData)));
I get what I was expecting...
255
216
255
Can't unpack give this to me itself without having to use oct()?
As a side note: I think I'm getting the 2's compliment of these byte integers when using "x$pos N1". I'm expecting these as the first 3 bytes.
255
216
255
Thanks again for the help to all.
Special thanks to @brian d foy and @muteW ... I now know how to access the Nth byte of my binary scalar using unpack(...). I have a new problem to solve now, which isn't related to this question. Again thanks for all the help guys!
This gave me the desired result...
print(unpack("x0 C1", $thisByteData));
print(unpack("x1 C1", $thisByteData));
print(unpack("x2 C1", $thisByteData));
unpack(...) has a ton of options so I recommend that anyone else who reads this read the pack/unpack documentation to get the byte data result of their choice. I also didn't try using the Tie options @brian mentioned, I wanted to keep the code as simple as possible.