home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / lang / perl / 7695 < prev    next >
Encoding:
Text File  |  1993-01-06  |  2.3 KB  |  67 lines

  1. Newsgroups: comp.lang.perl
  2. Path: sparky!uunet!spillman!tye
  3. From: tye@spillman.uucp (E. Tye McQueen)
  4. Subject: Does Perl need fgets()?
  5. Message-ID: <1993Jan07.013650.35727@spillman.uucp>
  6. Date: Thu, 07 Jan 1993 01:36:50 GMT
  7. Organization: Spillman Data Systems
  8. Lines: 57
  9.  
  10. Perl has two major ways of reading from a file, <handle> and sysread().
  11. I think fgets() would be a very handy addition.
  12.  
  13. First, some review:
  14.  
  15. <handle> is buffered so it doesn't work in many cases.  For example,
  16. when you want to use tell() to remember where the (next) line began
  17. so you can come back to it later.  Or if you want to read the first
  18. few lines until you get to the good part and then fork()+exec() to
  19. let some other program handle the rest of the input.
  20.  
  21. In both cases <handle> usually reads and buffers some "random" number
  22. of characters past the end of the line.  These characters are "lost"
  23. to the program you fork()+exec() and tell() gives the position after
  24. these random number of characters, not at the end of the line.
  25.  
  26. Okay, no suprises there.  That is why you don't use <handle> in such
  27. cases (okay, so it surprises me each time I run into it, but that's
  28. not what I meant).
  29.  
  30. Now, to get around this problem you write:
  31.  
  32.     # Read 1 new-line-terminated record w/o buffering or read-ahead
  33.     sub getline {
  34.       local( $hndl )= @_;
  35.       local( $rec, $cnt )= ( "", 0 );
  36.         do {
  37.             sysread( $hndl, $rec, 1, $cnt );
  38.         } while(  "\n" ne substr($rec,$cnt++,1)  );
  39.         $rec;
  40.     }
  41.  
  42. But doing this quickly is not Perl's strong suit.  (Yes, this can
  43. probably be tweaked for better speed, feel free to post suggestions
  44. and timing benchmarks.)
  45.  
  46. So how about:
  47.  
  48.     fgets( handle, buf[, maxlen[, off] )
  49.  
  50. for such cases?  If maxlen wasn't specified it would call fgets()
  51. repeatedly with some default buffer size (512 or so?) until it got
  52. a newline.
  53.  
  54. Alternately, there could be some way to change the behavior of
  55. <handle> so it would act this way (something like $|=1).
  56.  
  57. Any better ideas?
  58.  
  59. I wouldn't have mentioned it but this is the second time I've run
  60. into this and a coworker also ran into it today.
  61.  
  62. Thanks,
  63.  tye@spillman.com                         Tye McQueen, E.
  64. ----------------------------------------------------------
  65.  Nothing is obvious unless you are overlooking something. 
  66. ----------------------------------------------------------
  67.