9

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

类型、水果、描述、数量
热带,香蕉,美味可口,5
热带,葡萄柚,苦而不好吃,2
... 等等

首先,我想为每个“类型”、“水果”、“描述”、“数量”创建哈希哈希,并将不同的值存储在参考哈希中。这适用于下面的代码。

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)中,这将是一个包含每个哈希哈希列的表('Type'、'Fruit'、'描述','数量')。

4

2 回答 2

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

}
于 2012-11-28T14:40:47.757 回答
2

对于编写 Excel 文件 - 您可以使用Spreadsheet::WriteExcel

关于 CSV 文件 - 最初您拥有带有“,”分隔符和“\n”字符串分隔符的 CSV 文件。如果您想将一些 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);
于 2012-11-27T17:00:59.700 回答