On Mar 26, 10:17 am, [EMAIL PROTECTED] (Dennis G. Wicks) wrote: > Thanks for that. > > Maybe not "sneaky" but definitely very clever! > > That solved my problem a lot easier than I thought > it could be. > > Again, Thanks! > Dennis > > Chas. Owens wrote the following on 03/25/2008 08:50 PM: > > > On Tue, Mar 25, 2008 at 9:22 PM, Dennis G. Wicks <[EMAIL PROTECTED]> wrote: > >> Greetings, > > >> I get data in CSV files from several different sites > >> and I can't get the date/time formats to be consistent, > >> let alone have the fields arranged in the same order. > > >> I can put in the field/column names by hand in a first > >> record but I can't find hoe to go about using them to > >> change my split operation to get the info from the > >> right place depending on the first record that I will > >> add to the file. > > >> eg. one file will have columns name,title,phone, > >> snail-mail-addr,email while another file will have > >> name,email,phone,title. I can certainly change the perl > >> program, but as often as I would have to change it the > >> failure rate woould be pretty high! > > >> I am certain there is some sneaky perl trick that will > >> accomplish this, but I haven't been able to find it! > > snip > > > I wouldn't call it sneaky, but you could use a hash to store your > > records and use a hash slice to load the data into the hash: > > > #!/usr/bin/perl > > > use strict; > > use warnings; > > > chomp(my $header = <DATA>); > > my @fields = split /,/, $header; > > > while (<DATA>) { > > my %rec; > > @[EMAIL PROTECTED] = split /,/; > > print "name is $rec{name}, date is $rec{date}, status is > > $rec{status}\n"; > > } > > > __DATA__ > > name,date,status > > foo,2007-01-01,Done > > bar,2007-01-02,Working > > baz,2007-01-03,Invalid
A word of caution. If your fields have embedded commas (e.g. "there is a comma this string, also"), you should use something like the parse_line function from the Text::ParseWords package as opposed to split. HTH, Ken -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/