我试图从CSV文件打印数组的所有值.我在下面的例子中手动执行此操作.有人可以向我展示为阵列的所有字段执行此操作的代码,无论有多少字段?我基本上只是想在一个新行上打印每个字段.
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV_XS;
my $file = 'test.csv';
my $csv = Text::CSV_XS->new ({
quote_char => '"',
escape_char => '@',
binary => 1,
keep_meta_info => 0,
allow_loose_quotes => 1,
allow_whitespace => 1,
});
open (CSV, "<", $file) or die $!;
while (<CSV>) {
if ($csv->parse($_)) {
my @columns = $csv->fields();
print "$columns[0]\r\n";
print "$columns[1]\r\n";
print "$columns[2]\r\n";
print "$columns[3]\r\n";
print "$columns[4]\r\n";
print "$columns[5]\r\n";
print "$columns[6]\r\n";
print "$columns[7]\r\n";
}
else {
my $err = $csv->error_input;
print "Failed to parse line: $err";
}
}
close CSV;
Run Code Online (Sandbox Code Playgroud)
Ali*_*tra 15
foreach(@columns)
{
print "$_\r\n";
}
Run Code Online (Sandbox Code Playgroud)
而不是所有列[数字].
出于调试目的,Data::Dump是我的首选武器.它基本上可以打印数据结构.
use strict;
use warnings;
use Data::Dump 'dump';
# Do some stuff....
dump @array; # Unlike Data::Dumper, there's no need to backslash ('\@array')
dump %hash; # Same goes for hashes
dump $arrayref;
dump $hashref; # References handled just as well
Run Code Online (Sandbox Code Playgroud)
当然,还有许多其他方法可以打印数组:
say foreach @columns; # If you have Perl 5.10+
print $_,"\n" foreach @columns; # If you don't
print "@columns"; # Prints all elements, space-separated by default
Run Code Online (Sandbox Code Playgroud)
"最佳"答案取决于具体情况.你为什么需要它?你在忙什么?你想要它做什么?然后相应地调整代码.
如果您只想打印由空格分隔的元素:
print @columns;
Run Code Online (Sandbox Code Playgroud)
如果你想要更加花哨,你可以使用join:
print join("\n", @columns);
Run Code Online (Sandbox Code Playgroud)
如果您需要做更多的事情,请迭代它:
foreach (@columns) {
# do stuff with $_
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55487 次 |
| 最近记录: |