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).
精彩评论