一度に4バイトを読み取り、それを個々のバイトに分割し、それらを交換して、再度書き出すことができます。
#! /usr/bin/perl
use strict;
use warnings;
open(my $fin, '<', $ARGV[0]) or die "Cannot open $ARGV[0]: $!";
binmode($fin);
open(my $fout, '>', $ARGV[1]) or die "Cannot create $ARGV[1]: $!";
binmode($fout);
my $hexin;
my $n;
while (($n = read($fin, $bytes_in, 4)) == 4) {
my @c = split('', $bytes_in);
my $bytes_out = join('', $c[2], $c[3], $c[0], $c[1]);
print $fout $bytes_out;
}
if ($n > 0) {
print $fout $bytes_in;
}
close($fout);
close($fin);
これは、コマンドラインで次のように呼び出されます。
perl script.pl infile.bin outfile.bin
outfile.bin
上書きされます。