[Israel.pm] CSV

Offer Kaye oferk at oren.co.il
Wed Feb 25 00:48:07 PST 2004


>
> Hello,
>
> I have a large CSV file containing personal information about clients in
> the following format:
>
> # Input Blocks
> category,class,service,month,year
> A23,class A,subcontract,jan,2003
> ,id,sex,year,lastname,middlename,firstname,
> ,33,male,1980,last,middle,first
> ,34,female,1981,last,middle,first
>
> I want to make it appear this way:
>
> # Output Blocks
> category,class,service,month,year,id,sex,year,lastname,middlename,
> firstname,
>
> A23,class A,subcontract,jan,2003,33,male,1980,last,middle,first
> A23,class A,subcontract,jan,2003,34,female,1981,last,middle,first
>
> Does any one have any good idea of processing such file, my knowledge in
> PERL is not that much so my traditional way of solving this problem
> didn't help.
> P.S. The Input Blocks are listed one after the other.
>
> Best Regards,
> Georges
>

Assuming your input file is called "input.csv", here is some simplistic
code:
<code>
open(IN,"input.csv") or die "Couldn't open input.csv for reading: $!\n";
my @csv_input = <IN>;
close(IN);
my $lcount = 0;
while ($lcount <= $#csv_input){
   if ($csv_input[$lcount] =~ m/^category,class,service,month,year/) {
      my @in_block;
      push @in_block,$csv_input[$lcount];
      while ((($lcount+1) <= $#csv_input) &&
        ($csv_input[$lcount+1] !~ m/^\s*$/) &&
	($csv_input[$lcount+1] !~ m/^category,class,service,month,year/) ) {
         ++$lcount;
	 push @in_block,$csv_input[$lcount];
      }
      chomp @in_block;
      print $in_block[0],$in_block[2],"\n\n";
      for my $n (3..$#in_block) {
         print $in_block[1],$in_block[$n],"\n";
      }
      print "\n";
      next;
   }
   ++$lcount;
}
</code>

The code is simplistic because it assumes exactly the input format you
specified. Note also that it prints to standard output.
The code does assume that input blocks can be either seperated by empty
lines or not seperated at all (the conditions for the inner while). If
anything else is not clear just ask :)
Regards,
----------------------------------
Offer Kaye




More information about the Perl mailing list