This is how I would do that, with Data::Dumper output for comparison.

#!/usr/bin/perl -w use strict; use warnings; use Data::Dumper; open my $fh, '<', $ARGV[0] or die $!; my @lines = <$fh>; close $fh; my %data; for my $line (@lines) { my @fields; @fields = split /\s+/, $line; $data{$fields[1]}{$fields[0]} = $fields[2]; } for my $key (keys %data) { print "$key = $data{$key}\n"; for my $subkey (keys %{$data{$key}}) { print "\t$subkey = $data{$key}{$subkey}\n"; } } print Dumper(\%data);

Here is a sample run and the data.

my@mybox:~/sandbox $ ./2.pl data.txt jones = HASH(0x40017524) jenny = circle ted = circle knight = HASH(0x4001738c) ted = triangle $VAR1 = { 'jones' => { 'jenny' => 'circle', 'ted' => 'circle' }, 'knight' => { 'ted' => 'triangle' } }; my@mybox:~/sandbox $ cat data.txt ted jones square ted jones circle ted knight triangle jenny jones circle

The key differences from Perl Best Practices :

And also just the general idea of don't make global what can be local in scope ($key, $subkey, and @fields).

I did, violate the "Prefer line-based I/O to slurping," rule because we both know the sample data is tiny.


In reply to Re: Assign and print Hash of hashes by jffry
in thread Assign and print Hash of hashes by sundeep

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.