Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
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.Item1--Item2--Item3 ItemX--Item2--ItemA Item1--ItemV--Item3--Item4
This seems kind of clunky and error prone to me though.#!/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; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
•Re: Generating Hashes from arrays of arbitrary size
by merlyn (Sage) on Sep 30, 2004 at 17:07 UTC | |
by Anonymous Monk on Sep 30, 2004 at 17:11 UTC | |
by Roy Johnson (Monsignor) on Sep 30, 2004 at 18:14 UTC | |
|
Re: Generating Hashes from arrays of arbitrary size
by dragonchild (Archbishop) on Sep 30, 2004 at 17:09 UTC | |
|
Re: Generating Hashes from arrays of arbitrary size
by jdporter (Paladin) on Sep 30, 2004 at 17:08 UTC | |
|
Re: Generating Hashes from arrays of arbitrary size
by ikegami (Patriarch) on Sep 30, 2004 at 17:03 UTC | |
by graff (Chancellor) on Oct 01, 2004 at 02:44 UTC | |
by ikegami (Patriarch) on Oct 01, 2004 at 05:40 UTC |