开发者

Perl script to print out cars model and car color

I am tying to create a perl script to printout ca开发者_开发知识库r models and colors, and the data is below. I want to know if there is anyway to make the car model heading a field so that I can print it any time I want to? the data below is a csv file. the way I want the data to look on a report is below as well

********This is how the data looks********

Chevy
blue,1978,Washington 
brown,1989,Dallas
black,2001,Queens
white,2003,Manhattan

Toyota
red,2003,Bronx
green,2004,Queens
brown,2002,Brooklyn
black,1999,Harlem

***********This is how I am trying to get the data to look in a report***********

Car Model:Toyota

Color:Red Year:2002 City: Queens


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";
}


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 = $_;
  }  
}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜