in reply to Re^3: Question about binary file I/O
in thread Question about binary file I/O

Okay, I have a new file-related problem...what's the best way to read a certain number of bytes (say, 12) beginning at a certain position in a file (say, position 40), possibly reading them into an array and possibly performing operations on them, then write the result to a certain position in another file. I thought I had something, but I didn't...I don't even see a function in Perl for overwriting a string of bytes in a file, let alone know how to do the rest.

Replies are listed 'Best First'.
Re^8: Question about binary file I/O
by roboticus (Chancellor) on Mar 02, 2011 at 11:13 UTC

    TheMartianGeek:

    From perlvar you can read a specified amount of data by locally setting $/. You can move a file handle to a specific file location using seek, so you can do something like (untested):

    use strict; use warnings; use Fcntl qw( SEEK_SET ); . . . my @bytes; { my $input_location = 40; local $/=12; # Read 12 bytes open my $INF, '<', 'foo' or die; seek($INF, $input_location, SEEK_SET); my $t = <$INF>; @bytes = split //, $t; } # Do something with them @bytes = shuffle @bytes; # Write them to another file open my $OUF, '<+', 'bar' or die; my $output_location=1234; seek($OUF, $output_location, SEEK_SET); print $OUF, join("", @bytes);

    Generally, when I'm looking for ideas on how to do something, I scan perlfunc, perlvar and (of course) CPAN!

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

    Update: Changed to SEEK_SET (which is more likely to be the useful one) and also applied seek to input file, since he mentioned it in the OP.