0

I am reading 'Beginning Perl: Online book by Simon Cozen'. In my code below, print comment prints all lines of my data.txt file. But my while loop does not print anything. Please help me fix this problem.

open(FILE,'data.txt');
my $line = <FILE>;
my @lines = <FILE>;
print @lines;

while (<FILE>) {
    print "$_";
}
Mint.K
  • 849
  • 1
  • 11
  • 27
  • 1
    Note that you should use the 3-arg `open`, perform an error check, and use a lexical file handle instead of a bareword one: `open my $fh, '<', 'file.txt' or die $!;` – stevieb Mar 08 '17 at 15:36

1 Answers1

5

Since you've read the file and now you're "at the end", you need to close the file and open it again to get back to the start.

Alternatively, use seek FILE, 0, SEEK_SET; on the open file to reset back to the start without a close and reopen. (Use use Fcntl qw( SEEK_SET ); to import SEEK_SET.)

ikegami
  • 367,544
  • 15
  • 269
  • 518
John3136
  • 28,809
  • 4
  • 51
  • 69
  • You can also do `seek $fh, 0, 0;` to get the same effect. – stevieb Mar 08 '17 at 15:34
  • 1
    @stevieb, Sure, you could replace the meaningful constant with an obscure magical number instead, but that would be silly. – ikegami Mar 08 '17 at 17:10
  • Original answer had `seek FILE, 0, 0;`, it has been edited a couple of times since. I know "0, 0" worked since then I think we've had `SEEK_CUR` (which sounds to me like "current"? and now `SEEK_SET` This question ,ay be interesting reading (it was for me) http://stackoverflow.com/questions/16556332/perl-seek-function – John3136 Mar 08 '17 at 22:08