开发者

Refreshing line reading operator Perl

开发者 https://www.devze.com 2023-01-26 09:00 出处:网络
what happens after the eof is reached with <> operator in perl? I\'m reading INP1 line by line with

what happens after the eof is reached with <> operator in perl?

I'm reading INP1 line by line with

while(<INP1>) {
}

bu开发者_开发问答t I need to do this reading multiple times and I need to start from the beginning of the file each time. How can I do that? Is there something like refreshing the stream in perl?

Thanks in advance.


If INP1 is connected to a regular filehandle (not a socket handle or pipe handle), you can also seek back to the beginning of the file.

while(<INP1>) {
   ...
}
seek INP1, 0, 0;

# do it again
while (<INP1>) {
   ...
}

Another option is to load the entire file into an array one time, and then loop through that array as often as you wish. This is a good idea if the whole file fits comfortably in memory and if the contents of the file won't change between traversals.

open INP1, '<', $the_file;
@INP1 = <INP1>;
close INP1;

foreach (@INP1) {
   ...
}

# do it again
foreach (@INP1) {
   ...
}


In addition to using seek to go back to the start of the file, you could use Tie::File to treat the file as an array of lines. Depending on your access pattern, this might be more efficient than re-reading the file from the start each and every time.


You can seek back to the beginning:

use Fcntl;
open INP1, ...
while (<INP1>) {
}
seek INP1, 0, SEEK_SET;
while (<INP1>) {
}

This will only work properly if INP1 is a real file (not a pipe or socket).

0

精彩评论

暂无评论...
验证码 换一张
取 消