I'm doing a data conversion project. I've written a lot of this kind of script. This first script reads in a comma-separated-value file, which contains lines which look like:

productid,long description goes here,acctnumber

It reads the file and creates two associative arrays for the second and third fields, keyed by the first field

#!/usr/bin/perl use warnings; use strict; use vars qw/ %descs %salesAccts /; open(UPRODFILE,'<uprod.csv'); while (<UPRODFILE>) { chomp; my $prodID = ""; my $desc = ""; my $salesAcct = ""; ($prodID,$desc,$salesAcct) = split(/,/); # print "$prodID -- $desc -- $salesAcct \n"; $descs{$prodID} = $desc; $salesAccts{$prodID} = $salesAcct; } close(UPPRODFILE); #foreach my $i (sort keys %descs) { # print "$i == $descs{$i} == $salesAccts{$i} \n"; #} 1;

Then there's a second script that reads a second file, looks up each line in the two associative arrays, and creates a third file in the same format as the first.

#!/usr/bin/perl require 'uprod.pl'; while (<>) { chomp; print "$_, $descs{$_}, $salesAccts{$_}\n" }

This one runs in sloppy mode because I didn't want to generate warnings for cases where there was missing data. Usually I have warnings and strict turned on in every script - it just promotes better coding.

N.B. This requires that none of the fields in the first file contain embedded commas. If they do, this would have to be re-written using the Text::CSV module, which I have used on occasion, but avoid when unnecessary.

For me this is much faster and more predictable than using MS Excel with vlookup or something like that.


In reply to quickie table lookup by dreamgear

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.