in reply to Remove Extra bytes at end of file

Possibly unrelated, but while you set your output to binmode, you didn't do the same for your input. Also, reading a binary file a "line" at a time makes no sense. Change
my $data=''; while (<$file>) { $data .= $_; }
to
binmode($file); my $data; { local $/; $data = <$file>; }