2012-08-06 77 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