Reputation: 43
I am trying to swap two bytes at a time in a file. So I was thinking I could read in two bytes at a time and use reverse to switch the bytes around. However I am not sure how to read two bytes at a time in perl. Can someone make a suggestion
Upvotes: 0
Views: 219
Reputation: 385839
Reading two bytes at a time is hugely inefficient. You should continue to read larger blocks at a time and process the bytes in the buffer.
$buf =~ s/(.)(.)/$2$1/sg;
or
$buf = pack 'S<*, unpack 'S>*', $buf;
Upvotes: 1
Reputation: 1017
Use "read" (http://perldoc.perl.org/functions/read.html) to read and pass "2" for the LENGTH parameter to read 2 bytes (by default) of data.
For performance reasons, if you have a large file, you might want to consider reading more (or perhaps all) of the file once, instead of calling read ((filesize in bytes)/2) times.
Upvotes: 0