supriyoch_2008 has asked for the wisdom of the Perl Monks concerning the following question:
Hi PerlMonks,
I am interested to find out the lowest value (2) from an array i.e. @values=qw/5 3 2 9 2/; and to find the corresponding animal name(s) associated with the lowest value (2) from the array @names=qw/Cat Bat Cow Dog Rat/. I have written the following script key1.pl to find the lowest value, the position of the lowest value and then to call the animal name by position. The cmd gives the correct result for position 4(Rat) and not for 2(Cow). Since the lowest value 2 appears at two positions in the array, the correct result should be Cow (position 2) and Rat (position 4). I am at my wit's end to get the correct result. May I request perlmonks to provide some suggestions. I know that %hash can be used but use of %hash appears a little complicated to me. In fact, I tried using %hash but failed. Then I have tried using the given approach i.e. lowest value->position-> calling the name.
Here goes the code for key1.pl
#!/usr/bin/perl use warnings; ## To find lowest value and to call by reference: @values=qw/5 3 2 12 2/; @names=qw/Cat Bat Cow Dog Rat/; # To find the lowest value from the array A: $min=999; foreach my $item (@values) {$min=$item if $min > $item;} print"\n\n Lowest value= $min\n"; # To find the position of LOWEST Value(2) in Array values: @array_element_pos{@values}=(0..$#values); $i=$array_element_pos{$min}; print"\n Positions of Lowest Value(2)= $i (should be 2 & 4)\n"; # To extract corresponding animal name from Array names: print"\n The animal names are (should be Cow & Rat): ".$names[$i]."\n" +; exit;
I have got the following wrong results:
C:\Users\x>cd desktop C:\Users\x\Desktop>key1.pl Lowest value= 2 Positions of Lowest Value(2)= 4 (should be 2 & 4) The animal names are (should be Cow & Rat): Rat
But the correct results should look like:
Lowest value= 2 Positions of Lowest Value(2)= 2 4 (should be 2 & 4) The animal names are (should be Cow & Rat): Cow Rat
|
---|