Geetha Weerasooriya am Freitag, 15. September 2006 15:52: > Hi , > > I have an Array of Hashes as follows: > > @array = ( > { 'A'=>1, 'B' =>2, 'C'=>3, 'D'=>4} > { 'A'=>5, 'B' =>6, 'C'=>7, 'D'=>8} > { 'A'=>9, 'B' =>10, 'C'=>11, 'D'=>12} > { 'A'=>13, 'B' =>14, 'C'=>15, 'D'=>16} > { 'A'=>17, 'B' =>18, 'C'=>19, 'D'=>20} > { 'A'=>21, 'B' =>22, 'C'=>23, 'D'=>24} > ) > > I have given a reference to this array in my script. > > I want to do some calculation with only one key of each hash. For > example, I want to subtract from the value of key 'B' of last hash all > the other values of the same key into a one column like follows > > 22-2 20 > 22-6 16 > 22-10 12 > 22-14 8 > 22-18 4 > 22-22 0 > > Can you please tell me how to do this ?
Hi Geetha (again :-) Here's a slightly shorter version of J.W.Krahn's: #!/usr/bin/perl use strict; use warnings; my @array = ( { A => 1, B => 2, C => 3, D => 4 }, { A => 5, B => 6, C => 7, D => 8 }, { A => 9, B => 10, C => 11, D => 12 }, { A => 13, B => 14, C => 15, D => 16 }, { A => 17, B => 18, C => 19, D => 20 }, { A => 21, B => 22, C => 23, D => 24 }, ); # avoids multiple recalculation of the same value: # my $the_main_value=$array[ -1 ]->{ B }; for my $hash ( @array ) { print $the_main_value - $hash->{ B }, "\n"; } __END__ Suppose you want to use this principle for several arrays, you can make a procedure: #!/usr/bin/perl use strict; use warnings; my @array = ( #... ); sub my_calculation { my $array_ref=shift; my $the_one_value=$array_ref->[ -1 ]->{ B }; for my $hash ( @$array_ref ) { print $the_one_value - $hash->{ B }, "\n"; } } my_calculation ([EMAIL PROTECTED]); __END__ maybe you want to generalize the sub a bit: # ... sub my_calculation { my ($array_ref, $keyname)[EMAIL PROTECTED]; my $the_one_value=$array_ref->[ -1 ]->{ $keyname }; for my $hash ( @$array_ref ) { print $the_one_value - $hash->{ $keyname }, "\n"; } } # ... my_calculation ([EMAIL PROTECTED], 'B'); __END__ greets Dani -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>