Perl:Join / Splits-未初始化的变量

时间:2012-08-06 11:19:54

标签: perl

我正在尝试在从CSV文件读入的行的开头和结尾添加引号,然后拆分并添加到数组中

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

并导致:

"a,b,c"

"x,y,z"

我的数据看起来像我的数据:

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

我使用的代码是:

my @lines = join("\"", split (qr{<br\s?/>})), $line;    

我认为哪种方法可行,但我一直在努力:

"Use of uninitialized value $_"

我正在试图找出如何解决这个问题,我认为它(对某些人来说)将是一件我想念的简单事。

额外信息

我知道如果我想在开头添加引号并且完成我会使用:

push (@lines, "\"");
    unshift (@lines, "\"");

    my $newStr = join $/, @lines;
    print $newStr;

完整的代码是:

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;

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

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

    #Removes the control character.   
    shift (@lines); 
    print "\n";
    #print $_, $/ for @lines;
  }         
  print "\n Finished reading and formating: $ARGV[0] \n";
}
else { 
  print "Error: File is not a CSV file\n"
}

2 个答案:

答案 0 :(得分:3)

首先:在所有程序中始终 use strict


其中一个右括号位于错误的位置。

my @lines = join("\"", split (qr{<br\s?/>})), $line;
                                           ^-- The second arg of split goes here.

您所做的是,将隐式$_拆分为<br/>,然后使用$line作为新分隔符将结果列表与"一起加入。

这看起来像是:

$line = 'a<br/>b<br/>c';
# split...
# Result: a"b"c"a<br/>b<br/>c

请改用:

my @lines = join('"', split(qr{<br\s?/>}, $line));  

事实上,你可以完全忽略括号。 Perl会在这种情况下弄明白。我也改变了引用。如果你 使用单引号,您无需转义"符号。

my @lines = join '"', split qr{<br\s?/>}, $line;

示例:

my $line = 'a<br/>b<br/>c'; 
my @lines = join "\"", split qr{<br\s?/>}, $line;
print Dumper \@lines;

输出:

$VAR1 = [
          'a"b"c'
        ];

另请注意,join采用列表并返回单个字符串,而不是数组。

答案 1 :(得分:2)

我想知道你的数据是否真的看起来像这样

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

在这种情况下你需要的是

my @lines = split m|<br\s*/>|, $line;
print qq("$_"\n) for grep /\S/, @lines;

但是你的信息不一致,我只在这里猜测