On Thu, May 7, 2009 at 05:45, Raymond Wan <rwan.w...@gmail.com> wrote:
> Hi all,
>
> I would like to write binary values to disk (as well as read them) but don't
> know how to do it.  In C-speak, something like this:
>
> unsigned int foo = 42;
> fwrite (&foo, sizeof (unsigned int), 1, stdout);
>
> I think the answer involves something with pack and unpack, but I'm
> completely lost as I have no experience with either.  The closest I got was
>
> my $decimal_number = 42;
> my $binary_number = unpack("B32", pack("N", $decimal_number));
> print "Decimal number " . $decimal_number . " is " . $binary_number .
> " in binary.\n\n";
>
> which I've taken from
> http://www.linuxconfig.org/Perl_Programming_Tutorial.  This doesn't
> work since it's printing the number "42" in text binary; but
> I think it is close...  Or I might be barking up the wrong tree and I should
> be thinking about "fprintf" somehow...
>
> Does anyone have any ideas?  Thank you!
>
> Ray
>

You use pack to create a binary value and unpack to read a binary
value.  So, to write a file containing three 32 bit integers you say

#!/usr/bin/perl

use strict;
use warnings;

my $file = "/tmp/3ints";

#the :raw here tells Perl that the file will
#be binary
open my $fh, ">:raw", $file
        or die "could not open $file: $!\n";

print $fh pack "lll", 1230, -897, 20;

close $fh or die "could not close $file: $!\n";

my $size = (stat $file)[7];

print "$file contains $size bytes\n";


And then to read the file, you say:

#!/usr/bin/perl

use strict;
use warnings;

my $file = "/tmp/3ints";
my $size = 12;

#the :raw here tells Perl that the file will
#be binary
open my $fh, "<:raw", $file
        or die "could not open $file: $!\n";

sysread($fh, my $buffer, $size) == $size
        or die "did not read $size bytes from $file\n";

close $fh or die "could not close $file: $!\n";

print "the ints are ", join(", ", unpack "lll", $buffer), "\n";


-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to