Search code examples
perlstdinloops

How can I reopen STDIN <> in perl?


How can I open STDIN for the second time?

Let say I have this data

John Smith  25  O   ATG 180
Peter Jackson   40  AB  GGTA    173
Carl Anderson   32  A   GGT 172

And I have this code

while( my $line = <>)  {
    print $line;
}
while( my $line = <>)  {
    print $line;
}

I want it to print

John Smith  25  O   ATG 180
Peter Jackson   40  AB  GGTA    173
Carl Anderson   32  A   GGT 172
John Smith  25  O   ATG 180
Peter Jackson   40  AB  GGTA    173
Carl Anderson   32  A   GGT 172

Solution

  • You can't, you have emptied the stream. If you want to use it again, put the lines in an array.

    my @lines;
    while( my $line = <>)  {
        print $line;
        push @lines, line;
    }
    
    foreach my $line (@lines)  {
        print $line;
    }
    

    Or, write to a file and get a filehandle on the file.