title: Perl: Reading binary file one byte at a time
body: <p>I'm writing a tool that needs to read a binary file one byte at a time, process each byte, and potentially take some action depending on the processed value. But for some reason the values Perl is getting are not the same as the data in the file. I'm using code similar to this (stripped down for brevity, but this still exhibits the issue):</p>
  <pre><code>#!/usr/bin/perl
  use strict;
  
  my $bytesToProcess = 16;
  my $fileName = 'datafile.bin';
  
  print &quot;Processing $bytesToProcess bytes...\n&quot;;
  
  open FILE, &quot;&lt;:raw&quot;, $fileName or die &quot;Couldn't open $fileName!&quot;;
  
  for my $offset (0 .. $bytesToProcess - 1)
  {
      my $oneByte;
      read(FILE, $oneByte, 1) or die &quot;Error reading $fileName!&quot;;
      printf &quot;0x%04X\t0x%02X\n&quot;, $offset, $oneByte;
  }
  
  close FILE;
  </code></pre>
  <p>Input values (first 16 bytes of data file): <code>50 53 4D 46 30 30 31 35 00 00 70 00 07 3F 10 00</code></p>
  <p>Output:</p>
  <pre class="lang-none prettyprint-override"><code>Processing 16 bytes...
  0x0000  0x00
  0x0001  0x00
  0x0002  0x00
  0x0003  0x00
  0x0004  0x00
  0x0005  0x00
  0x0006  0x01
  0x0007  0x05
  0x0008  0x00
  0x0009  0x00
  0x000A  0x00
  0x000B  0x00
  0x000C  0x00
  0x000D  0x00
  0x000E  0x00
  0x000F  0x00
  </code></pre>
  <p>What's going wrong here?</p>