为什么我的Perl脚本会说“无法调用方法解析未定义的值”?

时间:2012-08-07 10:41:22

标签: perl csv

我是Perl的新手,仍在努力弄清楚如何用这种语言编写代码。

我目前正在尝试将一长串单个csv分成多行。

数据示例

a,b,c<br />x,y,x<br />

我到目前为止已经设法拆分,添加引号,以后再添加到CSV文件中:

"a,b,c""x,y,z"

通过引号,它只表示哪些CSV组合在一起。

我遇到的问题是,当我尝试创建CSV文件时,在字符串中传入数据时出现错误

  

“无法在未定义的变量上调用方法”解析“。

当我打印出我传入的字符串时,它被定义并保存数据。我希望这很简单,因为缺乏经验我做错了。

我使用的CSV代码是:

use warnings;
use Text::CSV;
use Data::Dumper;
use constant debug => 0;
use Text::CSV;

print "Running CSV editor......\n";

#my $csv = Text::CSV->new({ sep_char => ',' });

my $file = $ARGV[0] or die "Need to get CSV file on the command line\n";

my $fileextension = substr($file, -4);

#If the file is a CSV file then read in the file.
if ($fileextension =~ m/csv/i)
{   
    print "Reading and formating: $ARGV[0] \n";

    open(my $data, '<', $file) or die "Could not open '$file' $!\n";

    my @fields;
    my $testline;
    my $line;

    while ($line = <$data>) 
    {       
        #Clears the white space at the end of the line.
        chomp $line;

        #Splits the line up and removes the <br />.
        $testline = join "\" \" ", split qr{<br\s?/>}, $line;

        #my $newStr = join $/, @lines;
        #print $newStr;
        my $q1 = "\"";
        $testline = join "", $q1,$testline,$q1;
        print "\n printing testline: \n $testline \n";

    } 

    $input_string = $testline;

    print "\n Testing input string line:\n $input_string";

    if ($csv->parse ($input_string)) 
    {
     my @field = $csv->fields;

     foreach my $col (0 .. $#field) {
         my $quo = $csv->is_binary ($col) ? $csv->{quote_char} : "";
         printf "%2d: %s%s%s\n", $col, $quo, $field[$col], $quo;#
        }
    }
    else 
    {
     print STDERR "parse () failed on argument: ",
         $csv->error_input, "\n";
     $csv->error_diag ();
     }
    #print $_,$/ for @lines;

print "\n Finished reading and formating: $ARGV[0] \n";
}else
{   
    print "Error: File is not a CSV file\n"
}

1 个答案:

答案 0 :(得分:4)

您没有创建Text::CSV对象,但尝试使用它。

  

“无法在未定义的变量上调用方法”解析“

这意味着您的$csv不存在,因此它没有名为parse的方法。只需首先在代码顶部的所有Text::CSV行下方创建一个use对象。

my $csv = Text::CSV->new;

请注意Text::CSV的CPAN文档。


另外,我是否应该提及 use strict

相关问题