Use a while loop rather than a foreach loop. foreach will read the entire file before anything happens because it provides a list context to the diamond operator (<DATASOURCE>). And you can let perl keep track of the line number for you because it's in the special variable $.:

#!/usr/bin/perl use strict; use warnings; my $datasource ="C:\\somelargetextfile.txt"; open DATASOURCE, "$datasource" or die "Can't open $datasource: $!"; while (my $line = <DATASOURCE>){ print "$. - $line"; } close (DATASOURCE);

If this is all that your code is doing then I assume you're running on Windows because if you were on a unix, you could just use the cat(1) command to do something similar:

cat -n my_large_text_file.txt

Update: Ah, I see from your other post that you're inserting info into a database. Other than not reading the entire file into memory there isn't much else that you're going to be able to do to speed up the loop.

Why do you care how fast this program runs? Will it be run often? Must it finish within some time constraint so that it won't hold up a larger process?


In reply to Re: speeding up script that uses filehandles by duff
in thread speeding up script that uses filehandles by Anonymous Monk

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.