Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: build hash from csv file

by dragonchild (Archbishop)
on Sep 19, 2005 at 13:29 UTC ( #493158=note: print w/replies, xml ) Need Help??

in reply to build hash from csv file

First off, the hash you're building is ... wonky. Why not just use an array of arrays instead of a hash of hashes? All your keys are numbers ... that indicates you really want an array, not a hash.

Second, unless your CSV format is vastly different than the ones I'm used to, your s/"//g; will LOSE information, badly. Like, it'd be trivial to make a correct CSV file that would make your code break.

Much better is to let a CPAN module do this for you. I like tilly's Text::xSV best, but Text::CSV_XS is perfectly acceptable. (Text::CSV isn't feature-complete.)

use Text::xSV; sub build_hash { my ($file_) = @_; my $reader = Text::xSV->new(); $reader->open_file( $file_ ); my @result; while ( my $row = $reader->get_row() ) { push @result, $row; } return @result; }
If you absolutely have to have a hash of hashes, then you could do something like:
use Text::xSV; sub build_hash { my ($file_) = @_; my $reader = Text::xSV->new(); $reader->open_file( $file_ ); my %result; my $line = 0; while ( my $row = $reader->get_row() ) { # @{ $result{ ++$line } }{ 1 .. scalar(@$row) } = @$row; $line++; for my $i ( 1 .. @$row ) { $result{$line}{$i} = $row->[ $i-1 ] } } return %result; }
That commented-out wonky line is a hash-slice. It's exactly equivalent (but faster) than the 4 lines below.

My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

Replies are listed 'Best First'.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://493158]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2018-07-22 20:48 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (455 votes). Check out past polls.