CSV to Hash

I have csv, in the first column there is a label followed by values ​​separated by commas:

LabelA,45,56,78,90
LabelB,56,65,43,32
LabelC,56,87,98,45

I would like the first column (LabelA, etc.) to be the key in the hash with the numeric values ​​in the array.

I can read the file into an array or scalar, but I'm not sure what to do after that. Suggestions??

Edit: So it looks like this is assigning a value to the key ... but what about semicolons in my example? Where are they going? Are they in% hash? If you could further explain your explanation? Thanks.

+3
source share
4 answers

Well, let's say that special characters, etc. no.

First you open the file:

open my $fh, '<', 'some.file.csv' or die "Cannot open: $!";

Then you read from it in a loop:

while (my $line = <$fh>) {

Then you remove the trailing white characters (\ n and others):

$line =~ s/\s*\z//;

:

my @array = split /,/, $line;

, :

my $key = shift @array;

:

$hash{$key} = \@array;

(\ @array ).

:

my %hash;
open my $fh, '<', 'some.file.csv' or die "Cannot open: $!";
while (my $line = <$fh>) {
  $line =~ s/\s*\z//;
  my @array = split /,/, $line;
  my $key = shift @array;
  $hash{$key} = \@array;
}
close $fh;
+6

Text::CSV_XS IO:: :

use Text::CSV_XS;
use IO::File;

# Usage example:
my $hash_ref = csv_file_hashref('some_file.csv');

foreach my $key (sort keys %{$hash_ref}){
   print qq{$key: };
   print join q{,}, @{$hash_ref->{$key}};
   print qq{\n};
}

# Implementation:
sub csv_file_hashref {
   my ($filename) = @_;

   my $csv_fh = IO::File->new($filename, 'r');
   my $csv = Text::CSV_XS->new ();

   my %output_hash;

   while(my $colref = $csv->getline ($csv_fh))
   {
      $output_hash{shift @{$colref}} = $colref;
   }

   return \%output_hash;
}
+10

. perlfunc split perldsc.

  • .
  • Chomp it.
  • .
  • HoA.
  • .
  • .
  • ...
  • Profit!!!

:

:

my %foo = (
    LabelA => [  2, 3,  56, 78, 90 ],
    LabelB => [ 65, 45, 23, 34, 87 ],
    LabelC => [ 67, 34, 56, 67, 98 ],
);
+1

:: CSV:: Hashify

CSV Perl:

# Simple functional interface
use Text::CSV::Hashify;
$hash_ref = hashify('/path/to/file.csv', 'primary_key');

# Object-oriented interface
use Text::CSV::Hashify;
$obj = Text::CSV::Hashify->new( {
        file        => '/path/to/file.csv',
        format      => 'hoh', # hash of hashes, which is default
        key         => 'id',  # needed except when format is 'aoh'
        max_rows    => 20,    # number of records to read; defaults to all
        ... # other key-value pairs possible for Text::CSV
} );

# all records requested
$hash_ref       = $obj->all;
0

Source: https://habr.com/ru/post/1710804/


All Articles