2012-11-27 32 views
8

我有一個程序,目前從文件1讀取看起來像下面一個和匹配某些字符。 e.g寫從一個哈希Perl文件的CSV文件

Type, Fruit, Description, quantity 
tropical, banana, tasty and yummy, 5 
tropical, grapefruit, bitter and not yummy, 2 
... and so on 

首先我想爲每一個「類型」,「水果」,「說明」,「量」創建哈希散列和存儲在參考哈希值不同的值。這與以下代碼正常工作。

use strict; 
use warnings; 
use Data::Dumper; 
use Text::CSV; 

my %MacroA = ('Type' => {}, 'Fruit' => {}, 'Description' => {}, 'Quantity' => {});   

open (my $file, '<', 'FRUITIES.txt') or die $!;  

while (my $line = <$file>)                {           

if ($line =~ /\b(tropical)\b,/) {         
$MacroA{Type}->{$1}++; 
} 

if ($line =~ /,\b(banana|grapefruit)\b,/) {        
$MacroA{Fruit}->{$1}++; 
} 

if ($line =~ /,([\w\s]+?),/) {         
$MacroA{Description}->{$1}++; 
} 

if ($line =~ /,([\d]+?)/) {        
$MacroA{Quantity}->{$1}++; 
} 
     } 

close $file;      

所以我的問題是我怎樣才能把這個數據(數據是不固定的)到CSV文件或相關的任何事情(也許XLS),這將是與哈希每個哈希列的表(」類型','水果','描述','數量')。

+3

您是否嘗試過運行您的代碼?它有編譯錯誤。你應該先解決它們,然後看看[Text :: CSV](http://p3rl.org/Text::CSV)(你似乎已經發現了你自己)。 – simbabque

+0

hi @simbabque是的,這不是原始代碼,它只是一個例子。我看了一下Text :: CSV,但不知道如何使用它。 –

+0

@El_Commandantee如果只是爲了您的使用,或者您可以編寫'髒'代碼,沒有模塊和其他東西,您可以編寫使用Perl核心函數的代碼easy – gaussblurinc

回答

3

我同意哈希散列是一件好事,但我想你」不要以您可以輕鬆檢索的方式存儲它。

你可以做到的一種方式就是這樣。

{ id_1 => { 
      data_1 => "blah", 
      data_2 => "foo", 
      ... 
      }, 
    id_2 => { 
      ... 
      }, 
    ... 
} 

首先,你需要選擇哪一列是「ID」。這將決定每個ROW的唯一性。舉個例子,讓我們選擇果實,因爲我們假設沒有兩個水果會出現在同一個文件中。所以我們會這樣的:

{ banana => { 
      type => "tropical", 
      description => "tasty and yummy", 
      ... 
      }, 
    grapefruit => { 
      ... 
      }, 
    ... 
} 

爲了把它改回到CSV,我們循環遍歷散列。

my %fruit_data; #let's assume that this already has the data in it 

foreach my $fruit (keys %fruit_data) { 

    #given the $fruit you can now access all the data you need 
    my $type = %fruit_data{$fruit}{'type'}; 
    my $desc = %fruit_data{$fruit}{'description'}; 
    # etc... 

    # then you may want to store them in a scalar in any order you want 
    my $row = "$field,$type,$desc etc.\n"; 

    # then work your way from there 

} 
2

要編寫Excel文件 - 您可以使用Spreadsheet::WriteExcel

關於CSV文件 - 最初您的CSV文件帶有「,」分隔符和「\ n」字符串分隔符。如果你想寫hashrefs到CSV的一些陣列 - 更好的方式自行寫下簡單的分,未便像這樣的:

use strict; 
use warnings; 

sub write_csv { 

    my ($array_ref, $fh) = @_; 

    for my $row (@$array_ref) { 
    print $fh join(',', map { $_, $row->{$_} } sort keys %$row), "\n"; 
    } 
} 

my $test = [ 
    {a => 1, ab => 2, type => '234k', count => '123'}, 
    {a => 3, ab => 2, type => 'some_type', count => 34}, 
]; 

open my $fh, '>', 'test.csv' or die $!; 

write_csv($test, $fh); 
+2

其中,粗糙的,在包含分隔符的任何單元上失敗。 – ugexe

+2

我認爲發起人必須來自那些對這個代碼有多麼模糊的印象深刻的人。它當然不回答問題 – Borodin

+0

感謝您的好公關,男人。它至少回答了這個問題的部分 - 如何用Perl編寫excel文件,以及如何編寫CSV文件 - 如果您可以調整代碼,它會給出正確答案的總體方向。根據需求編寫自定義CSV文件看起來更像是一個自由職業,而不僅僅是一個問題。 – moonsly