Writing to a CSV file from a perl hash

I have a program that is currently reading from FILE 1 , as shown below, and matches specific characters. eg

  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 a hash of the hashes for each Type, Fruit, Description, Quantity, and store different values ​​in the hashes of the links. This works well 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; 

So my question is: How can I put this data (the data is not corrected) in a csv file or something related (maybe xls), this will be a table with columns for each hash of the hashes ('Type', "Fruit", "Description ", "Number" ).

+8
perl csv hash
source share
2 answers

I agree that hash hashes are good, but I think you don't store it the way you can easily get it.

One way to do this is this.

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

First of all, you need to choose which column will be β€œID”. This would define the uniqueness of each ROW. Let me say that your example allowed you to select a fruit, since we assume that there will not be two fruits that appear in the same file. So, we would have something like this:

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

To change this to CSV, we scroll through the hashes.

 my %fruit_data; #let 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 } 
+3
source share

You can use the Table :: WriteExcel to write Excel files.

About CSV files - initially you have a CSV file with line separators "," and "\ n". If you want to write some hashrefs array for CSV is the best way to write a simple sub yourself, smth, like this:

 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
source share

All Articles