File-Binary

 view release on metacpan or  search on metacpan

lib/File/Binary.pm  view on Meta::CPAN


$VERSION='1.7';

# for seekable stuff
$DEBUG = 0;

# set up some constants
$BIG_ENDIAN     = 2;
$LITTLE_ENDIAN  = 1;
$NATIVE_ENDIAN  = 0;

# and export them
@EXPORT_OK = qw($BIG_ENDIAN $LITTLE_ENDIAN $NATIVE_ENDIAN guess_endian);


=head1 NAME

File::Binary - Binary file reading module

=head1 SYNOPSIS

    use File::Binary qw($BIG_ENDIAN $LITTLE_ENDIAN $NATIVE_ENDIAN);

    my $fb = File::Binary->new("myfile");
    
    $fb->get_ui8();
    $fb->get_ui16();
    $fb->get_ui32();
    $fb->get_si8();
    $fb->get_si16();
    $fb->get_si32();

    $fb->close();

    $fb->open(">newfile");

    $fb->put_ui8(255);
    $fb->put_ui16(65535);
    $fb->put_ui32(4294967295);
    $fb->put_si8(-127);
    $fb->put_si16(-32767);
    $fb->put_si32(-2147483645);
    
    $fb->close();


    $fb->open(IO::Scalar->new($somedata));
    $fb->set_endian($BIG_ENDIAN); # force endianness

    # do what they say on the tin
    $fb->seek($pos);
    $fb->tell();

    # etc etc


=head1 DESCRIPTION

B<File::Binary> is a Binary file reading module, hence the name, 
and was originally used to write a suite of modules for manipulating 
Macromedia SWF files. 

However it's grown beyond that and now actually, err, works. 
And is generalised. And EVERYTHING! Yay!

It has methods for reading and writing signed and unsigned 8, 16 and 
32 bit integers, at some point in the future I'll figure out a way of 
putting in methods for >32bit integers nicely but until then, patches 
welcome.

It hasn't retained backwards compatability with the old version of this 
module for cleanliness sakes and also because the old interface was 
pretty braindead.

=head1 METHODS

=head2 new

Pass in either a file name or something which isa an IO::Handle.

=cut 

sub new {
    my ($class, $file) = @_;

    my $self = {};
    
    bless $self,  $class;

    $self->open($file);
    $self->set_endian($NATIVE_ENDIAN);


    return $self;
}

=head2 open

Pass in either a file name or something which isa an IO::Handle.

Will try and set binmode for the handle on if possible (i.e
if the object has a C<binmode> method) otherwise you should do
it yourself.

=cut 

sub open {
    my ($self, $file) = @_;
    
    my $fh;
    my $writeable = -1;

    if (ref($file) =~ /^IO::/ && $file->isa('IO::Handle')) {
        $fh = $file;
        $writeable = 2; # read and write mode 
    } else {
        $fh = IO::File->new($file) || die "No such file $file\n";
        if ($file =~ /^>/) {
            $writeable = 1;
        } elsif ($file =~ /^\+>/) {
            $writeable=2;



( run in 2.423 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )