in reply to Re^4: Perl binary file reading
in thread Perl binary file reading

my @r = <$fh>; my $data = join '', @r;

That's a waste of memory, because you have the file content in both @r and $data. The usual idiom is:

my $data=do { local $/; <$fh> };

This reads the file contents directly into $data, without any splitting, joining, or temporary arrays. See Perl Idioms Explained - my $string = do { local $/; <FILEHANDLE> };.

See also The parable of the falling droplet to remember what $/ and $\ do.

Alexander

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

Replies are listed 'Best First'.
Re^6: Perl binary file reading
by kepler (Scribe) on May 03, 2016 at 13:33 UTC

    Hi Alexander

    That code is really awesome :)

    Thank you very much.

    "Read" gives me for some reason a problem with some particular byte - I didn't had the time to isolate it. It works - I've read correctly some more extra records for that matter. Still, I can't get the whole file. Maybe is from the fact I'm running Perl in my Windows 7, and might have some disconfiguration in the system... Either way my "malformed" solution worked - but yours is even better, simplier and... actually nice and clean. Thanks.

    Regards, Kepler

      "Read" gives me for some reason a problem with some particular byte - I didn't had the time to isolate it.

      Are you sure that binmode is enabled?

      Both ...

      open my $fh,'<:raw',$filename or die "Could not open $filename: $!"; my $data=do { local $/; <$fh> };

      ... and ...

      open my $fh,'<',$filename or die "Could not open $filename: $!"; binmode $fh; my $data=do { local $/; <$fh> };

      ... should do the trick. The first one requires a perl with support for I/O layers (introduced somewhere in the 5.8.x series, IIRC), the second one should also work with older perls. And this one is for really ancient perls:

      local *FH; open FH,"<$filename" or die "Could not open $filename: $!"; binmode FH; my $data=do { local $/; <FH> };

      See also Using ":raw" layer in open() vs. calling binmode() and PerlIO.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)