Perl脚本打印出汽车模型和汽车颜色
我正在创建一个perl脚本来打印汽车模型和颜色,并且数据如下。我想知道是否有任何方法可以让汽车模型驶向某个领域,以便随时随地打印它?以下数据是一个csv文件。我想要的数据看报表上的方式是下面还有Perl脚本打印出汽车模型和汽车颜色
********这是数据的外观********
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城市:皇后区
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 = $_;
}
}
这不会在严格使用下运行,所有代码都应该使用。此外,建议使用3-arg打开。 – 2010-06-16 09:15:49
我会去通过文件一行一行地对各行(伪代码,未测试):
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文件中的空行,然后就换行来分隔其他车型
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";
}
哇,使用数组作为哈希键...? – Brian 2010-06-15 21:31:11
@Brian:这被称为散列片。 http://www.perlcircus.org/hashes.shtml – 2010-06-15 21:33:21
我想在make上打印(对不起,你是对的),然后列出所有车辆下的所有车辆,而不是每辆车重复。 例如 雪佛兰 车资讯信息 车资讯信息 车资讯信息 车资讯信息 福特 车资讯信息 车资讯信息 车资讯信息 车资讯信息 丰田 车资讯信息 车信息info 汽车信息信息 汽车信息信息 感谢您的帮助 – 2010-06-16 14:24:32
您可以使用Text::CSV读取CSV文件。该模块将捕获在您自己的实现中可能会漏掉的所有边缘情况。
查看perldoc perldsc和perldoc perldata以获取有关perl数据结构的帮助。
到目前为止你有什么代码? – Ether 2010-06-15 21:22:07
像“丰田”和“雪佛兰”这样的名称是汽车*制造*,而不是车型。模型就像“凯美瑞”或“塔霍”。 – 2010-06-15 21:47:35
那么你想为每条数据行重复make行吗?或者你想为每组数据行创建一次make行吗?第一种选择似乎是你从当前的回应中得到的,但我怀疑你真正想要的是第二种选择。不幸的是,你的输出示例只显示一行数据,因此很难说出预期的结果。 – 2010-06-16 03:12:06