Prior to reading the line the first time, call tell. That will give you the current position in the file. Then after reading the line, you can call seek using the data you already retrieved with tell() to rewind back to the same line.

Another alternative is to use Tie::File to handle the details for you, and just treat the file like an array, which makes it much easier to move back and forth between various lines.

Update:
I just wanted to provide an example of my method (which jettero refers to as an absolute method):

use strict; use warnings; open my $fh, '<', 'testfile.txt' or die $!; my $position = tell $fh; while ( defined( my $line = <$fh> ) ) { print "First read:\t $line"; seek $fh, $position, 0 or die $!; my $reread = <$fh>; print "Second read:\t $reread"; } continue { $position = tell $fh; } close $fh;

The preceding snippet opens a file, reads and prints each of its lines twice. Of course it's sort of pointless; once you've read a line one time why read it again? It's easier to store the read value than to re-read it. Storing your previous position is just as much work as storing the read value, while storing the read value avoids two IO calls. But that's beside the point. ;)


Dave


In reply to Re: reading a line from file two times by davido
in thread reading a line from file two times by jesuashok

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.