5

Very similar to Changing one byte in a file in C, but in Perl instead of C.

How can I open a binary file in Perl, change ONLY the first byte, and write it back out?

Community
  • 1
  • 1
We Are All Monica
  • 12,312
  • 7
  • 43
  • 71

2 Answers2

12
open my $fh, '+<', $file      or die "open failed: $!\n";
my $byte;
sysread($fh, $byte, 1) == 1   or die "read failed: $!\n";
seek($fh, 0, 0);
syswrite($fh, $new_byte) == 1 or die "write failed: $!\n";
close $fh                     or die "close failed: $!\n"; 
Eugene Yarmash
  • 131,677
  • 37
  • 301
  • 358
  • You're missing a `"` on the syswrite line, but it looks like this will (correctly) die on zero-byte files. I wouldn't have thought of that, thanks. – We Are All Monica Mar 17 '10 at 18:44
6

Many ways to do it. An efficient way is to open the file in random access mode with open $fh, '+<':

my $first_byte = chr(14);      # or whatever you want the first byte to be
open my $fh, '+<', $the_file;
seek $fh, 0, 0;                # optional - cursor is originally set to 0
print $fh $first_byte;         # could also use  write  or  syswrite  functions
close $fh;
mob
  • 114,178
  • 18
  • 142
  • 274