perl - Text::CSV bind_columns 不起作用

标签 perl csv text

当我使用此代码时,它不会显示任何输出。它只打印表格标签。我有什么遗漏的吗?

这是我的 csv 文件:

id;name;city;
1;name;london;
5;testname;newyork;
7;users;amsterdam;
8;test1234;eindhoven;

这是我的 Perl 脚本:

#!C:\perl64\bin\perl.exe -wT
use strict;
use warnings;
use CGI;
use CGI::Carp qw/fatalsToBrowser/;
use CGI qw(:standard);
use Text::CSV_XS;

print "Content-Type: text/html\n\n";
my $file = 'import.csv';
my $csv = Text::CSV_XS->new({
    'quote_char'  => '',
    'escape_char' => '',
    'sep_char'    => ";",
    'binary'      => 1,
    'eol'         => $/
});

$csv->bind_columns (
                \my $id,
                \my $name,
                \my $city);

open my $fh, "<", $file or die "$file: $!";
print "<table border='1'>";
while($csv->getline($fh)){
    print "
        <tr>
            <td>$id</td>
            <td>$name</td>
            <td>$city</td>
        </tr>";
}
print "</table>";

最佳答案

the documentation对于bind_columns,您可以阅读以下内容:

Takes a list of references to scalars to store the fields fetched getline () in. When you don't pass enough references to store the fetched fields in, getline () will fail.

实际上,您的行中有 4 个字段,但您在 bind_columns 中传递了 3 个引用。

id;name;city;  # fields "id", "name", "city" and ""

最后一个字段为空。如果您向 bind_columns 添加字段,您的代码将按预期工作。

$csv->bind_columns (
            \my $id,
            \my $name,
            \my $city,
            \my $blank
);

关于perl - Text::CSV bind_columns 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19134509/

相关文章:

linux - 为什么 perl 调试器找不到脚本找到的模块?

python - Pandas 读取 csv - 处理混合命名/无名列

sql - 使用 SQL 将文本文件导入通用数据库

python - 使用 pandas.read_csv 读取以空格为千位分隔符的 CSV 文件

perl - Perl 中的 `->` 语法是什么意思?

perl - Perl 单行语句可以在 Perl 脚本中使用吗?

regex - 在 Perl 正则表达式中使用包含特殊字符的变量

python - 打印乐谱 - Pygame

在 R 和 plot() 中读取阿拉伯数据文本

function - 在 Powershell 中从文本文件中随机化的更好方法