I now need to find a specific line in the file not only the first and last like the example shows(I know the suffix) is there a better way that to run on the (loop) array and find it ?
Last I heard (only a few days ago), davido was working on a module for CPAN, to use an index on a text file. You might want to use it when it becomes available.

In the meantime, here's one way you can do it by hand. The assumption is that the original data text file is not changed often.

First, here's how to create the index file:

open IN, "<", $textfile or die "Can't open textfile: $!"; binmode IN; open IDX, ">", "$textfile.idx" or die "Can't create index file: $!"; binmode IDX; print IDX pack "N", 0; while(<IN>) { print IDX, pack "N", tell IN; }

Next, here's how to look up a line by number (in $lineno):

open TEXT, "<", $textfile or die "Can't open textfile: $!"; open IDX, "<", "$textfile.idx" or die "Can't open index file: $!"; binmode IDX; seek IDX, 4*$lineno, 0; read IDX, my($buf), 4; seek TEXT, unpack("N", $buf), 0; $line = <TEXT>;
(update: fixed parameter order for seek)

As you may have guessed, the pack/unpack serves to make the integer index a fixed length (4 bytes).


In reply to Re: Reading from a file by bart
in thread Reading from a file by just dave

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.