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?

In reply to Re: build hash from csv file by dragonchild
in thread build hash from csv file by tcf03

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.