Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Save hash value?

by ig (Vicar)
on Jun 06, 2011 at 02:42 UTC ( #908231=note: print w/ replies, xml ) Need Help??


in reply to Save hash value?

You have another problem... not only are you modifying copies of your data rather than the original, but you are also modifying the array you are iterating over. This often leads to unexpected results. Consider the following:

use strict; use warnings; use Data::Dumper; my @array = (1..10); for (my $i = 0; $i <= $#array; $i++) { splice(@array, $i, 1); } print Dumper(\@array);

This produces:

$VAR1 = [ 2, 4, 6, 8, 10 ];

Maybe this is what you expected, or maybe you expected the array to be empty. In either case, I don't think your program will necessarily find all the duplicates.

If I couldn't avoid creating the duplicate entries for some reason, I might merge them with something like:

use strict; use warnings; use Data::Dumper; my @players = ( { name => 'name1', deaths => 2, kills => 5, }, { name => 'name2', deaths => 2, kills => 5, }, { name => 'name3', deaths => 2, kills => 5, }, { name => 'name2', deaths => 1, kills => 4, }, ); my %merged; foreach my $player (@players) { if(exists($merged{$player->{name}})) { $merged{$player->{name}}->{deaths} += $player->{deaths}; $merged{$player->{name}}->{kills} += $player->{kills}; } else { $merged{$player->{name}}->{deaths} = $player->{deaths}; $merged{$player->{name}}->{kills} = $player->{kills}; } } print Dumper(\%merged);

which produces

$VAR1 = { 'name2' => { 'deaths' => 3, 'kills' => 9 }, 'name1' => { 'deaths' => 2, 'kills' => 5 }, 'name3' => { 'deaths' => 2, 'kills' => 5 } };


Comment on Re: Save hash value?
Select or Download Code
Re^2: Save hash value?
by toxicious (Initiate) on Jun 06, 2011 at 19:02 UTC
    I completely understand what you mean, great that you pointed it out.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2014-07-13 05:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (247 votes), past polls