in reply to File::Binary:howto goto a position in file

What about this approach:
#! /usr/bin/perl use strict ; use Fcntl 'SEEK_SET'; use IO::Seekable; # not sure if this will help our @ISA = qw(IO::Seekable); open IN,"<fio.pl" ; binmode IN ; my $reclen = 1 ; my $binrec ; while ( read(IN, $binrec, $reclen) ) { print "".unpack("A",$binrec) ; } ....... # seek ?

Can I apply a seek via this approach ?

Luca

Replies are listed 'Best First'.
Re^2: File::Binary:howto goto a position in file
by ikegami (Patriarch) on Mar 12, 2006 at 17:41 UTC
    Close. Either use the OO approach (by creating an IO::File) or the functional approach, but forget this whole @ISA = qw(IO::Seekable) business.
    #! /usr/bin/perl use strict; use warnings; use Fcntl 'SEEK_SET'; open local *IN, "<", "fio.pl" ; # XXX Check for errors binmode IN ; my $reclen = 1 ; my $binrec ; while ( read(IN, $binrec, $reclen) ) { print "".unpack("A",$binrec) ; # XXX What's with '"".'? } seek(IN, 10, SEEK_SET); # or whatever

    Docs: seek

      Thnx, I've fixed it (without OO). If I try OO, like:
      #! /usr/bin/perl use strict ; use Fcntl 'SEEK_SET'; use IO::File ; my $fh = new IO::File ; $fh->open("fio.pl") ; $fh->binmode() ; $fh->setpos(4) ; my $in ; $fh->read($in,2) ; printf "result: %s\n",unpack("A2",$in) ; $fh->close() ;
      The output is: result: #! (thats no shift at all!)
      But I get the idea that the biggest mistake has been made with the read command....
      Also, what about perldoc IO::Handler:
      $io->read ( BUF, LEN, [OFFSET] )
      I miss the explanation of the 3 variables BUF, LEN and OFFSET ?

      Thanks
      Luca

      update: solved the seek issue: $fh->seek(5, SEEK_SET) ;
      I guess the only thing I don't understand is the OFFSET. If I give that a number I get nothing... ?

        I don't know how good IO::File's docs are, but check these docs (to which I already linked):

        The values for WHENCE [which you called OFFSET] are 0 to set the new position in bytes to POSITION, 1 to set it to the current position plus POSITION, and 2 to set it to EOF plus POSITION (typically negative). For WHENCE you may use the constants SEEK_SET , SEEK_CUR , and SEEK_END (start of the file, current position, end of the file) from the Fcntl module. Returns 1 upon success, 0 otherwise.

        In other words, the second argument determines whether the first argument is relative to the front of the file, to the current position in the file, or to the end of the file.