I THINK that this works. I would like to verify and get some suggestions to improve performance.

I have a file that contains hundreds of lines that look like this:
Item1--Item2--Item3 ItemX--Item2--ItemA Item1--ItemV--Item3--Item4
These lines can have any number of items in them. I need to put these into a hash to work with. The approach i am taking is to build each one into a hash reference and then merge it into the main hash.


This is the code that I have so far:
#!/usr/bin/perl -w use strict; use Data::Dumper; my $datafile = "data.txt"; open(FILE,$datafile); foreach my $line (<FILE>) { #Kill linefeeds/returns. Data generated on variety of OS's $line =~ s/\n//g; $line =~ s/\r//g; my @items = split(/--/,$line); my $foo = &bhash(\%shash,@items); @shash{keys %$foo} = values %$foo; } close(FILE); print Dumper \%shash; sub bhash { my($hash,@keys )= @_; my $ref= \$hash; map($ref= \$$ref->{$_}, @keys); return $$ref; }
This seems kind of clunky and error prone to me though.

In reply to Generating Hashes from arrays of arbitrary size by Anonymous Monk

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.