2012-08-06 34 views
0

我试图引号添加到开始并且已经被从CSV文件中读取一条线的终点,然后分裂,并加入到一个数组的Perl:加入/ Splits-未初始化的变量

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

并导致:

"a,b,c" 

"x,y,z" 

我的数据看起来像我的数据是这样的:

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

我我们的代码ING是:

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" 
} 
+0

是的,就是这样。 'split'作为默认参数'$ _'。你需要指定正确的行,你想通过'split'函数来分割。我会在你的情况下做到这一点:'split/delimiter /,$ splitThisLine' – gaussblurinc 2012-08-06 11:24:45

+0

请看我们可以看到一些* real *输入数据和你想要的相应输出吗?您没有显示任何包含“
”的内容。 我认为你让Perl和C混淆,因为你似乎认为你可以通过数组访问字符串的字符。 发生了什么是您正在创建一个'@ lines'数组,其中一个元素等于'join'的返回值。 你立即删除这个元素与调用'移动'与评论*删除控制字符*,因此数组结束为空 – Borodin 2012-08-06 12:00:22

+0

我已经添加了一个数据的例子,当然shit(@lines)删除第一个元素数组,在我的情况下是一个控制字符。 – QuinsUK 2012-08-06 12:46:56

回答

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接受一个列表并返回单个字符串,而不是阵列。

2

我不知道也许你的数据实际上看起来像这样

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

在这种情况下,你需要的是

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

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

+0

我的数据看起来像:a,b,c
x,y,z
QuinsUK 2012-08-06 12:25:52

+0

+1我在想同样的事情。整个'加入'“''部分非常奇怪......但我用完了时间,所以我没有在我的回答中跟着它。 – simbabque 2012-08-06 16:25:35

+0

@QuinsUK:那么我的两行代码应该适合你 – Borodin 2012-08-06 20:48:36