从散列perl写入CSV文件

El_*_*tee 9 csv perl hash

我有一个程序,目前从FILE 1读取,看起来像下面的那个,并匹配某些字符.例如

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

首先,我想为每个'Type','Fruit','Description','Quantity'创建哈希哈希,并将不同的值存储在引用哈希中.这适用于下面的代码.

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;                    
Run Code Online (Sandbox Code Playgroud)

所以我的问题是如何将这些数据(数据不是固定的)放入csv文件或任何相关的(可能是xls),这将是一个包含每个散列哈希列的表('Type','Fruit','描述','数量').

the*_*qbf 3

我同意哈希值的哈希值是一件好事,但我认为您没有以可以轻松检索它的方式存储它。

你可以这样做的一种方法是这样的。

{ id_1 => {
             data_1 => "blah",
             data_2 => "foo",
             ...
           },
  id_2 => {
             ...
           },
  ...
 }
Run Code Online (Sandbox Code Playgroud)

首先,您需要选择哪一列是“ID”。这将决定每个 ROW 的唯一性。假设您的示例中让我们选择水果,因为我们假设不会有两个水果出现在同一个文件中。所以我们会有这样的东西:

{ banana => {
             type => "tropical",
             description => "tasty and yummy",
             ...
           },
  grapefruit => {
             ...
           },
  ...
 }
Run Code Online (Sandbox Code Playgroud)

为了将其改回 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

}
Run Code Online (Sandbox Code Playgroud)