Read CSV file as array of hashes


The csv function that can be imported from Text::CSV can read a CSV into memory, creating an array of hashes.

Element from the first row will be used as the keys of these hashes and elements from all the other rows will be used as the values of these hashes.


examples/other/planets.csv
Planet name,Distance (AU),Mass
Mercury,0.4,0.055
Venus,0.7,0.815
Earth,1,1
Mars,1.5,0.107
Ceres,2.77,0.00015
Jupiter,5.2,318
Saturn,9.5,95
Uranus,19.6,14
Neptune,30,17
Pluto,39,0.00218
Charon,39,0.000254


examples/other/read_csv_as_array_of_hashes.pl
use strict;
use warnings;

use Text::CSV qw(csv);
use Data::Dumper qw(Dumper);

my $filename = 'planets.csv';
my $solar_system = csv(
    in => $filename,
    headers => 'auto');

print Dumper $solar_system;

$VAR1 = [
          {
            'Planet name' => 'Mercury',
            'Mass' => '0.055',
            'Distance (AU)' => '0.4'
          },
          {
            'Planet name' => 'Venus',
            'Mass' => '0.815',
            'Distance (AU)' => '0.7'
          },
          {
            'Distance (AU)' => '1',
            'Planet name' => 'Earth',
            'Mass' => '1'
          },
          {
            'Planet name' => 'Mars',
            'Mass' => '0.107',
            'Distance (AU)' => '1.5'
          },
          {
            'Planet name' => 'Ceres',
            'Mass' => '0.00015',
            'Distance (AU)' => '2.77'
          },
          {
            'Distance (AU)' => '5.2',
            'Mass' => '318',
            'Planet name' => 'Jupiter'
          },
          {
            'Distance (AU)' => '9.5',
            'Mass' => '95',
            'Planet name' => 'Saturn'
          },
          {
            'Distance (AU)' => '19.6',
            'Mass' => '14',
            'Planet name' => 'Uranus'
          },
          {
            'Mass' => '17',
            'Planet name' => 'Neptune',
            'Distance (AU)' => '30'
          },
          {
            'Distance (AU)' => '39',
            'Mass' => '0.00218',
            'Planet name' => 'Pluto'
          },
          {
            'Mass' => '0.000254',
            'Planet name' => 'Charon',
            'Distance (AU)' => '39'
          }
        ];