Perl hash arrays and some problems

I currently have a csv file that looks like this:

a,b
a,d
a,f
c,h
c,d

      

So, I saved them in a hash, so the key "a" is an array with "b, d, f" and the key "c" is an array with "h, d" ... that's what I used to this:

while(<$fh>)
{
 chomp;
 my @row = split /,/;
 my $cat = shift @row;
 $category = $cat      if (!($cat eq $category))  ;
 push @{$hash{$category}}, @row;
}

close($fh);

      

Not sure about efficiency, but it seems to work when I do Dump Dump ...

Now I have a problem: I want to create a new file for each key, and in each of these files, I want to print each item in the key, as such:

File "a" will look like this:   

b
d
f

<end of file>

      

Any ideas? Everything I've tried doesn't work, I'm not too familiar with hashes ...

Thank you in advance:)

+3


source to share


2 answers


The inference process is very simple using an iterator each

that provides a key and value pair for the next hash element in a single call



use strict;
use warnings;
use autodie;

open my $fh, '<', 'myfile.csv';

my %data;

while (<$fh>) {
   chomp;
   my ($cat, $val) = split /,/;
   push @{ $data{$cat} }, $val;
}

while (my ($cat, $values) = each %data) {
   open my $out_fh, '>', $cat;
   print $out_fh "$_\n" for @$values;
}

      

+5


source


#!/usr/bin/perl

use strict;
use warnings;

my %foos_by_cat;

{
   open(my $fh_in, '<', ...) or die $!;
   while (<$fh_in>) {
      chomp;
      my ($cat, $foo) = split /,/;
      push @{ $foos_by_cat{$cat} }, $foo;
   }
}

for my $cat (keys %foos_by_cat) {
   open(my $fh_out, '>', $cat) or die $!;
   for my $foo (@{ $foos_by_cat{$cat} }) {
      print($fh_out "$foo\n");
   }
}

      

I wrote an inner loop, as I did, to show the symmetry between read and write, but it can also be written like this:



print($fh_out "$_\n") for @{ $foos_by_cat{$cat} };

      

+5


source







All Articles