You will have to go through the entire file, there is no way around that. Unless you can calculate the exact spot you want to modify upfront.

The Perl CookBook gives several strategies for updating a file.

1. Read from the original file, output to a temporary file. Make the changes you want to the temporary file. Rename the temporary back to the original once you’re done. A snippet to explain the idea:

use strict; use warnings; my ($old, $new); open(OLD, "< $old") or die "can't open $old: $!"; open(NEW, "> $new") or die "can't open $new: $!"; while (<OLD>) { # Some logic... print NEW $_ or die "can't write $new: $!"; } close(OLD) or die "can't close $old: $!"; close(NEW) or die "can't close $new: $!"; rename($old, "$old.orig") or die "can't rename $old to $old.orig: $!"; rename($new, $old) or die "can't rename $new to $old: $!";

2. Use the -i and -p switches to Perl. This also creates a temporary file but Perl takes care of the file manipulation.

There are a few more like: "Updating the file in place without a temporary file" and "Updating a Random-Access File" but in your case (a small csv file) this seems like overkill to me.

Bless the CookBook!

BTW You have a lot of if/elsif statements. This can probably be improved upon. You might want to take a look at the Switch. Or use the ternary operator to improve the readability.

A last remark: there are many modules around on CPAN to work with CSV data. This might be the simplest/most elegant solution of all:-)

Hope this helps.


In reply to Re: Better Way to Search Large File. by dHarry
in thread Better Way to Search Large File. by walkingthecow

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.