Link to home
Start Free TrialLog in
Avatar of Hanqian
Hanqian

asked on

How to create an associative array at runtime in perl?

Dear Expert,

When I read a data file as format as follow at runtime
AA      1
AB      1
AC      1
AA      1
AD      1
AD      1


I need to create an associative array (AA->2,  AB->1, AC->1, AD->2) at runtime,  how should I do it?

Thanks.
Hanqian
Avatar of Adam314
Adam314

open(IN,"<filename.txt") or die "Couldn't open file: $!\n";
my %data;
while(<IN>) {
    my @f=split /\s*/;
    $data{$f[0]} += $f[1];
}
close(IN);

open(IN,"<filename.txt") or die "Couldn't open file: $!\n";
my %data;
while(<IN>) {chomp; $data{(split)[0]} += $data{(split)[1]}}
close(IN) ;
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It may be more fair to split the points,  all the suggestions work, I eliminated some unecesary operations, but used a deprecated feature.
I decided against recommending a split because of what I considered to be errors in the earlier posts.

A split on /\s*/ ends up being a split into _characters_ since \s* matches a null string, so I don't think Adam314's proposal works.

Doubling up the split call, with an unneeded (but admittedly harmless) call to chomp made me decide against Manav's proposal.

I didn't notice anything in your solution that I'd consider strongly deprecated, but I wonder whether it might not be better to have used a \n instead of a comma in your print.
You're right, I forgot that the first suggestion has used * instead of +, even though it was the reason I posted.  
The superfluousness of the second suggestion prompted a minimalist reaction even though
perldoc -f split
says that use of split in scalar context is  deprecated because it clobbers your subroutine arguments.
there are no subroutine arguments here, but one might be careful about using the same solutuon in other contexts.
I used comma because comma was used in the question.
<quote>
Doubling up the split call, with an unneeded (but admittedly harmless) call to chomp made me decide against Manav's proposal.
</quote>
I agree. It would be fair for the points to go to Ozo.