Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Assign and print Hash of hashes

by jffry (Hermit)
on Nov 22, 2010 at 06:19 UTC ( [id://872895]=note: print w/replies, xml ) Need Help??


in reply to Assign and print Hash of hashes

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 :

  • Don't use bareword file handles.
  • Use the three-argument form of open.
  • Use indirect file handles.
  • Close file handles explicitly, and as soon as possible.
  • Avoid C-style for statements.
  • Don't use unnecessary parentheses for builtins and "honorary" builtins.
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.

Replies are listed 'Best First'.
Re^2: Assign and print Hash of hashes
by sundeep (Acolyte) on Nov 22, 2010 at 17:30 UTC
    Dear Monk,

    Thanks for the reply and suggestions. I have one doubt here. You suggested me to use a 3 argument form of open, but yours and my file open, seem to be the same. Can you please tell me, what exact difference will it make in a 3 argument and a 2 argument file open?

      I'm quoting from Perl Best Practices, by Damian Conway, chapter 10, the "Open Cleanly" section.

      Using a three-argument open instead ensures that the specified opening mode can never be subverted by bizarre filenames, since the second argument now specifies only the opening mode...
      ...as a small side-benefit, each open becomes visually more explicit about the intended mode...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://872895]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-04-23 21:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found