Gossamer Forum
Home : General : Perl Programming :

Reading file into hash

Quote Reply
Reading file into hash
Hi,

I am trying to read the file with contents (below) into a hash :

File contents :
Set1|A B C
Set2|D E A
Set3|B C F
Set4|G H D
Set5|I J K
Set6|K L M
Set7|N O P

Here I want to have the entity before '|' as the key and entities after the '|' as values read into an array (so that I can access each of the elements(values) with array index.

Method that I am using :
my %sets;
open(DATAIN,"<$ARGV[0]") || die "cannot open \"$ARGV[0]\": $!";
while($line = <DATAIN>){
chomp $line;
($name, $element) = split(/\|/, $line);
push @{$sets{$name}}, $element;
print..... (examples given below)
}

Here I see that the values (eg., A B C in the first line of the input file) are read as array but when I try to access each one there seem to be a problem.
For example :
print "@{$sets{$name}}[0]\n";
gives me the whole array as
A B C
D E A
B C F
G H D
I J K
K L M
N O P

Which means its taking all elements as element '0' of the array which I do not want.

And using
print "@{$sets{$name}}[1]\n";
gives me error as :
Use of uninitialized value in join or string
and so on......

Ideally I would want to have (example for first line)
print "@{$sets{$name}}[0]\n"; # Give me 'A'
print "@{$sets{$name}}[1]\n"; # Give me 'B'
print "@{$sets{$name}}[2]\n"; # Give me 'C'

Thanks
Quote Reply
Re: [le_faquir] Reading file into hash In reply to
Hi,

Below should work,

Cheers,


In Reply To:
my %sets;
open(DATAIN,"<$ARGV[0]") || die "cannot open \"$ARGV[0]\": $!";
while($line = <DATAIN>){
chomp $line;
($name, $element) = split(/\|/, $line);
my @elements = splits(/\s+/,$element);
push @{$sets{$name}}, @elements;
print..... (examples given below)
}

Cheers,

Dat

Programming and creating plugins and templates
Blog