Newsgroups: comp.lang.perl Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!think.com!zaphod.mps.ohio-state.edu!van-bc!ubc-cs!uw-beaver!fluke!inc From: inc@tc.fluke.COM (Gary Benson) Subject: Re: Easy way to peek ahead in <> Message-ID: <1991May29.151541.1307@tc.fluke.COM> Organization: John Fluke Mfg. Co., Inc., Everett, WA References: <1991May29.004259.11825@dartvax.dartmouth.edu> Date: Wed, 29 May 91 15:15:41 GMT In article <1991May29.004259.11825@dartvax.dartmouth.edu> xerox@eleazar.dartmouth.edu (Jamie Osborne) writes: > >Is there any easy way to peek ahead using the while(<>) { >construct? I want to be able to read the next line, but I don't want >to advance <> yet. > >Help anyone? I do this, but I'm afraid that there isn't a way to avoid advancing <>. Instead, you trick it. For each line that you want to peek, put it into an array and keep track of the number of lines going in. Now, when you want to advance <>, look at the "lines" array first. If there's something in there, use it instead of <>; if there's nothing there, use the real <>. Here's my "peek" subroutine: #****************************************************************************** # PEEK Peek N lines ahead in the input stream. # sub peek { $tmp = $_; $i = $#lines+1; while ($i<$_[0] && !eof()) { $i++; $_ = <>; &prefilter(); push(@lines,$_); } $_ = $tmp; &prefilter(); if ($#lines >= $_[0]-1) { $lines[$_[0]-1]; } } #****************************************************************************** That's PART ONE. The second part involves how you send things to the output. Here's my "printline" subroutine: #****************************************************************************** # PRINT LINE Substitute special characters and then print the line. sub printline { # first, find the line to print, either passed in or default $tmp = $#_ < 0 ? $_ : $_[0]; &spec_char_subs($tmp); print OUTPUT $tmp; } #****************************************************************************** Hope that helps. -- Gary Benson -=[ S M I L E R ]=- -_-_-_-inc@fluke.com_-_-_-_-_-_-_-_-_-_- Selling software is like prostitution; you've got it, you sell it, you've still got it! -D. Lambert (IST)