perl - 从哈希 perl 写入 CSV 文件

标签 perl csv hash

我有一个程序,目前从 FILE 1 读取,如下所示并匹配某些字符。例如

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

First of all I wanted to create hash of hashes for each 'Type', 'Fruit', 'Description', 'Quantity' and store the different values in the reference hashes. That works fine with the code below.

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)中,这将是一个表,其中包含每个哈希值的列(“类型” 、“水果”、“描述”、“数量”)。

最佳答案

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

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

{ 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

}

关于perl - 从哈希 perl 写入 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13588129/

相关文章:

perl - 为什么将 Perl 哈希值添加为键?

python - 如何让 numpy 数组的 FFT 工作?

python - 如何从一个文件创建多个数据帧?

hash - 种子 info_hash 参数

ruby - 将 Ruby 数组转换为键值对的哈希值,其中值是常量

Perl 在 while 循环中挂起

perl - 在使用 ("Server1"时不能使用字符串 "strict refs") 作为 SCALAR ref

linux - 解析文件 perl

java - 如何解决InputStream LeftoverDataException : Initialisation of record 0x85 left 18 bytes remaining still to be read

ruby-on-rails - 将 ActiveRecord 查询结果作为具有所选属性的哈希数组获取