[comp.lang.perl] seek

frech@mwraaa.army.mil (Norman R. Frech CPLS) (06/30/90)

Could someone give a few details concerning the seek function?  I am dealing
with several files at the same time, accessing certain field from each file.
One of the things I wanted to do is hash out a record number for one of the
files and seek to that record to grab the data.  As far as I could tell
when I tried to seek to the location it was actually pushing forward the 
number of characters not the number of records.  Also, is the whence from
the last seek or from the beginning of the file or what?  What I ended up
going is sequentially accessing the file from the beginning and counting
down to the hashed address.  There has to be a faster way and I was hoping
the seek would provide the method I am looking for.  Any information would
be appreciated.

Norm Frech < frech@mwraaa.army.mil >

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (06/30/90)

In article <1990Jun29.171643.13413@uvaarpa.Virginia.EDU> frech@mwraaa.army.mil writes:
: Could someone give a few details concerning the seek function?  I am dealing
: with several files at the same time, accessing certain field from each file.
: One of the things I wanted to do is hash out a record number for one of the
: files and seek to that record to grab the data.  As far as I could tell
: when I tried to seek to the location it was actually pushing forward the 
: number of characters not the number of records.  Also, is the whence from
: the last seek or from the beginning of the file or what?  What I ended up
: going is sequentially accessing the file from the beginning and counting
: down to the hashed address.  There has to be a faster way and I was hoping
: the seek would provide the method I am looking for.  Any information would
: be appreciated.

The seek() works exactly like Unix's fseek(), which you could read the
manual page for.  In fact, Perl's seek() calls Unix's fseek().  Everything
is in bytes--Unix doesn't know what you mean by a record, and doesn't
want to know.  If your records are fixed length, you can calculate a byte
position in the file by multiplying the record number by the record size.
If they're not fixed length, you can't calculate a position, and you have
to come up with some way to remember the position (such as an index), or
find a way of guessing so that you'll find it eventually (like a binary
search or something).  (And that only works if the records are ordered and
you can recognize the beginning of records unambiguously.)  But there's
no way in Perl or Unix to say "Go to line X of a file" unless one of those
conditions are met.

The whence argument says where to count bytes from:

	0	From the beginning of the file
	1	From your current position in the file
	2	From the end of the file

Obviously with 1 and 2 you might be dealing with negative offsets.

Larry