home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.perl
- Path: sparky!uunet!spillman!tye
- From: tye@spillman.uucp (E. Tye McQueen)
- Subject: Does Perl need fgets()?
- Message-ID: <1993Jan07.013650.35727@spillman.uucp>
- Date: Thu, 07 Jan 1993 01:36:50 GMT
- Organization: Spillman Data Systems
- Lines: 57
-
- Perl has two major ways of reading from a file, <handle> and sysread().
- I think fgets() would be a very handy addition.
-
- First, some review:
-
- <handle> is buffered so it doesn't work in many cases. For example,
- when you want to use tell() to remember where the (next) line began
- so you can come back to it later. Or if you want to read the first
- few lines until you get to the good part and then fork()+exec() to
- let some other program handle the rest of the input.
-
- In both cases <handle> usually reads and buffers some "random" number
- of characters past the end of the line. These characters are "lost"
- to the program you fork()+exec() and tell() gives the position after
- these random number of characters, not at the end of the line.
-
- Okay, no suprises there. That is why you don't use <handle> in such
- cases (okay, so it surprises me each time I run into it, but that's
- not what I meant).
-
- Now, to get around this problem you write:
-
- # Read 1 new-line-terminated record w/o buffering or read-ahead
- sub getline {
- local( $hndl )= @_;
- local( $rec, $cnt )= ( "", 0 );
- do {
- sysread( $hndl, $rec, 1, $cnt );
- } while( "\n" ne substr($rec,$cnt++,1) );
- $rec;
- }
-
- But doing this quickly is not Perl's strong suit. (Yes, this can
- probably be tweaked for better speed, feel free to post suggestions
- and timing benchmarks.)
-
- So how about:
-
- fgets( handle, buf[, maxlen[, off] )
-
- for such cases? If maxlen wasn't specified it would call fgets()
- repeatedly with some default buffer size (512 or so?) until it got
- a newline.
-
- Alternately, there could be some way to change the behavior of
- <handle> so it would act this way (something like $|=1).
-
- Any better ideas?
-
- I wouldn't have mentioned it but this is the second time I've run
- into this and a coworker also ran into it today.
-
- Thanks,
- tye@spillman.com Tye McQueen, E.
- ----------------------------------------------------------
- Nothing is obvious unless you are overlooking something.
- ----------------------------------------------------------
-