On Mar 19, 12:43*pm, cerr <ron.egg...@gmail.com> wrote:
> Hi There,
>
> I read out the content from a file like:
> foreach $line (<$handle>) {
> * * * * * print $line;
> * * * * * sleep(1);
> * * * * }
> whixh works well so far. But what I would like is, if the loop gets to
> eof, it should start over on top again. How can i reset the reading
> pointer back to the beginning of the file?
If an infinite loop is what you want, you can always use the
Tie::File module (which you may already have in your installation of
Perl) and just increment the index variable, making sure to "mod" it
by the number of lines.
Here's an example:
#!/usr/bin/perl
use strict;
use warnings;
my $fileName = 'file.txt';
use Tie::File;
tie my @lines, 'Tie::File', $fileName
or die "Could not open file '$fileName': $!\n";
die "No lines found in '$fileName'.\n" unless @lines;
my $lineNum = 0;
while (1)
{
print $lines[$lineNum], "\n";
sleep(1);
}
continue
{
# Increment $lineNum, but make sure it doesn't exceed $#lines:
$lineNum++;
$lineNum %= @lines;
}
__END__
This solution may seem overkill for your example, but if you have a
more complex task where you'd rather traverse arrays instead of
manipulating file handles, Tie::File is quite nice.
Cheers,
-- Jean-Luc
|