tags:

views:

106

answers:

4
+1  A: 
open IN, "< somefile";
while (<IN>) {
  chomp;
  if (m/,/) {
    @temp = split /,/, $_;
    printf "Car model: %s\nColor: %s\nYear: %s\nCity: %s\n\n", $make, @temp;
  } else {
    $make = $_;
  }  
}
ray
This wouldn't run under use strict, which all code should be using. Also, 3-arg open is recommended.
David Precious
A: 

I would go through the file line by line and for each line (pseudo-code, not tested) :

if ($line ~= /\w+,\d+,\w+/) { # matches the lines with the information
    my $array = split $line at , 
    print to file array[0] + "," + array[1] + "," + array[2] + "\n"
} elsif ($line ~= /\w+/) { # matches the car model since the information was already matched
    print "Car Model:" + $line + "\n"
} else {   # must be the whitespace so you know the information about the car is done
    print "\n" # to separate the car information
}

If you don't have the blank line in your csv file then do the newline to separate the car models elsewhere

Kyra
+4  A: 
open my $fh, '<', 'filename' or die $!;

while (<$fh>) {
    next if /^\s*$/;
    my @fields = split /,/, $_;
    print("Car Model: $fields[0]\n"), next if @fields == 1;

    my %data;
    @data{qw( color year city )} = @fields;
    print "Color:$data{color} Year:$data{year} City:$data{city}\n";
}
eugene y
Woah, using an array as the key to a hash...?
Brian
@Brian: This is called hash slice. http://www.perlcircus.org/hashes.shtml
eugene y
I would like to print on make (sorry you are right) and then list all of the cars under that one make and not have it repeat for each car.examplechevycar info infocar info infocar info infocar info infoFordcar info infocar info infocar info infocar info infoToyotacar info infocar info infocar info infocar info infoThanks for your help
Gary Liggons
@Gary: check out the updated version
eugene y
open my $fh, '<', 'filename' or die $!;while (<$fh>) { next if /^\s*$/; my @fields = split /,/, $_; print("Car Model: $fields[0]\n"), next if @fields == 1; my %data; @data{qw( color year city )} = @fields; print "Color:$data{color} Year:$data{year} City:$data{city}\n";}this worked! thanks! how can I get the output so show up the same way if I wanted to make it a .html file?
Gary Liggons
+1  A: 

You can read in CSV files with Text::CSV. That module will catch all the edge cases that you are likely to miss in your own implementation.

Check out perldoc perldsc and perldoc perldata for help on perl data structures.

Ether