Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array of Hashes

Status
Not open for further replies.

loosecannon1

Programmer
Feb 19, 2002
55
US
Following is my compare loop that searches for two description keys that possess the same value.

Problem: If the evaluation is ever true I need to switch all values between the two AoH's. For example switch the values of $sortedPast[$i]{description} and $sortedPast[$z]{description} and so on for every key. How can I do this?

for $i(0..$#sortedPast) {
for $z(0..$#sortedPast) {
if ($i == $z) { $z++ }; # !compare same array
if ($sortedPast[$i]{description} eq $sortedPast[$z]{description}) {
# switch all values of $sortedPast[$i] and sortedPast[$z]
}
}
}

If my problem is unclear let me know.
loosecannon
 
you can do this:

my %temp;
%temp = %{$sortedPast[$i]};
%{$sortedPast[$i]} = %{$sortedPast[$z]};
%{$sortedPast[$z]} = %temp;
 
thks yauncin, your solution is just what I needed.

loosecannon
 
You can do it without all the for loops using Perl's built-in sort()

@sortedPast = sort {! $$a{description} cmp $$b{description}} @sortedPast;

Also, in your nested for loops, you should print out the values of $i and $z. The if statement that increments $z++ increments $z but doesn't actually increment the loop counter so you end up doing each value of $z twice and on the last iteration of the loop when $i and $z are equal you will increment $z beyond the end of the array.

jaa
 
Oops, the code i posted doesn't work like i thought it did. but by caveat is still true. you should check out all the values ot $z that are being evaluated through both loops. You should change the $z++ to

next if $i == $z;

I'll post back if i can get the sort() to work.

jaa
 
I also noticed that you are starting the $z forloop at 0. This will compare every pair of items in the array twice and since they are going to be equal both times that you compare them, they will be swapped twice. Therefore you will end up with the same array that you started with. You need to start $z at $i+1 instead of 0.

for my $i(0..$#sortedPast) {
for my $z($i+1..$#sortedPast) {
if ($sortedPast[$i]{description} eq $sortedPast[$z]{description}) {
($sortedPast[$i], $sortedPast[$z]) = (\%{$sortedPast[$z]}, \%{$sortedPast[$i]});
}
}
}

jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top