我想创建一个打印车型和颜色的perl脚本,数据如下。我想知道是否有任何方法让汽车模型朝向一个领域,以便我可以随时打印它?以下数据是csv文件。我希望数据在报告中查看的方式也在下面
********这是数据的外观********
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
***********这就是我试图让数据在报告中查找的方式***********
车型:丰田
颜色:红色年份:2002城市:皇后区
答案 0 :(得分:4)
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";
}
答案 1 :(得分:1)
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 = $_;
}
}
答案 2 :(得分:1)
您可以使用Text::CSV读取CSV文件。该模块将捕获您在自己的实现中可能会遗漏的所有边缘情况。
查看perldoc perldsc和perldoc perldata以获取有关perl数据结构的帮助。
答案 3 :(得分:0)
我会逐行检查文件和每行(伪代码,未经过测试):
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
}
如果您的csv文件中没有空白行,那么请使用换行符将汽车模型分开到别处