2013-07-18 25 views
1

我新的Perl和我需要寫一個perl腳本符合下列要求動態輸入一個值從CSV陣列(列):新到perl - 用perl

  1. 需要閱讀csv文件
  2. 商店中的陣列中的列
  3. 假設有7個字段(列)中的CSV:字段1,字段2,字段3,字段4,區域5,區域6,場7

我需要能夠給任何領域作爲輸入參數動態。假設如果我給輸入參數字段3,字段7和在CSV的數據是:

No of orders'|Date'|Year'|Exp_date'|Month'|time'|Committed 
12'|12122002'|2013'|02022012'|12'|1230'|Yes 

然後我想輸出是:

Year~Committed       
2013~Yes 

和剩餘的列也將在相同的格式:

No of orders~Date~Exp_date~Month~time 
12~12122002~02022012~12~1230 

目前我從網上一個Perl腳本,提供了我的左片面結果只在硬編碼格式。但我想在運行時給出輸入並希望生成結果。幫助表示感謝。

$filename = 'xyz.csv'; 

# use the perl open function to open the file 
open(FILE, $filename) or die "Could not read from $filename, program halting."; 

# loop through each line in the file 
# with the typical "perl file while" loop 
while(<FILE>) 
{ 

    chomp; 

    # read the fields in the current line into an array 
    @fields = split('\`\|', $_); 

# print the concat 
print "$fields[0]~$fields[1]\n"; 
} 


close FILE; 
+2

不要試圖用正則表達式解析CSV。改用'Text :: CSV'。 – innaM

+0

但即使我使用Text :: csv,是否可以將列作爲輸入參數? – jesse

+0

'Text :: CSV'逐行解析CSV文件,爲您提供一組字段。在這個腳本中,它將取代上面的'split()'命令。之後你如何操縱田地取決於你。 –

回答

0

我不打算爭論是否使用Text :: CSV。這與問題無關,split完全可以接受。

下面是我將如何解決這個問題,假設海報想要輸入多個數據行的文件。

#!/usr/bin/perl -w 

# take any file name from the command line, instead of hard coding it 
my ($filename) = @ARGV; 
my @title; 
my @table; 

open FILE, "<", $filename or die "Could not read from $filename, program halting."; 
while (<FILE>) { 
    chomp; 
    if ([email protected]) { 
    @title = split '\'\|'; 
    next; 
    } 
    my @row = split '\'\|'; 
    # build an array of array references, a two dimensional table 
    push @table, \@row; 
} 
close FILE; 

print "Access which row? "; 
my $row = <STDIN> - 1; 
die "Row value is out of range for $filename\n" if (($row < 0) || ($row >= scalar(@table))); 

print "Access which column? "; 
my $col = <STDIN> - 1; 
die "Column value is out of range for $filename\n" if (($col < 0) || ($col >= scalar(@title))); 

print "$title[$col]\~$table[$row][$col]\n"; 

while循環的第一遍將在我們的Title數組中存儲拆分值。剩下的遍將逐行添加我們的數據作爲數組引用。然後通過一些用戶提示和基本的錯誤檢查,我們打印出結果。