source.txt

Name|Address
Ram|USA
Geeta|India

I want to read this file into hash or map

The coulum headers should be stored as keys, and when i call the key it should say me Ram and whn i call Address as key it should say USA

Please let me know how can i do this in perl.

Recommended Answers

All 4 Replies

IMO it's best to use an array of hashes. Here is a version that works for what you wish. The hashes are put into an array, so each hash is in an array row:

use strict;
use warnings;
open(FILE,"<source.txt");
my $x=0;
my @keys;
my @holder;
my @array_hash;
while(<FILE>){
	chomp;
	$x++;
	if($x==1){
		(@keys)=split(/\|/);
	}else{
		my $y=0;
		(@holder)=split(/\|/);
		my %hash;
		for (@holder){
			$hash{$keys[$y]}=$_;
			$y++;
		}
		push @array_hash,\%hash;
	}
}
for (@array_hash){
	my $a=$_;
	for (keys %$_){
		print "$_ = $a->{$_} \n";
	}
	print "============\n";
}

Output:

Address = USA
Name = Ram
============
Address = India
Name = Geeta
============
commented: The OP's question seemed unclear to me. But good guess and good demo of AoH. +1

When looking at my own reply, I noticed that I assumed that you understand references, hashes, arrays and the standard perl variable assignment. So, I'd like to ask the forum, do we have to dumb down the solutions to match the skill level of our newbie posters? I believe that newbies can learn from more experienced perl coders regardless of their status. What do you all think?

In general I would try to tailor the complexity of the solution and extent of explanation to the apparent knowledge level of the person posing the question. However, figuring out what the poster needs to know is a two-way street. If someone posts a vague and hastily-written question and never adds any more comments or feedback, what can you do? If the question interests me and I can come up with a not-too-elaborate way to test my answer, I'll take a shot at it.

If the poster gives some further details or clarification I tend to make more effort to help than when someone just pops a question and disappears.

I'm really not sure what neerajte wanted. Names and addresses are not unique in the real world and keys to a hash have to be unique, but your solution works for the sample data and demonstrated the principle of using an array of hashes, so it may have served the purpose. If neerajte doesn't reply or mark the thread solved, we won't know for sure.

I am new to perl but your code has significantly helped me. Could you please explain the array of hashes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.