AlexAMP AlexAMP - 18 days ago 6
Perl Question

In Perl, how can find the smallest value in a list and keeping the index corresponding to that value?

I am looking to distinguish the difference between side_i and side_j to find the smallest value ... following on... to then multiply the smallest and largest by a given number.

That's pretty simple to do. However, I want to still be able to distinguish between i and j in such a way that I know which one is which after they have been multiplied.

This is what I have so far. Please note , I am a very new user of Perl and general coding:

use strict;
use Getopt::Long;
use List::Util qw(max);
use File::Find;
use warnings 'all';



my $side_i = 24.56;
my $side_j = 3.56;
my $maxi = 10;
my $maxj = 10;
my $threshold = 0.05;
my $small_side;



(my $sside, my $bside) = smallestTest($side_i, $side_j);


sub smallestTest{

my $sside;
my $bside;
print "$_[0] $_[1] /n";
if ($_[0]<$_[1]){
$sside = $_[0];
$bside = $_[1];
} else {
$sside = $_[1];
$bside = $_[0];
}
return($sside, $bside);
}
print "Biggest side is $bside /n";

my $newSide_i = $.....*20;
my $newSide_j = $.....*21;

Answer

I suggest that you use a hash %side to contain the values. Then the $sside and $bside variables can hold the identities i and j of the smallest and biggest values

You don't explain what you want to do after you've determined which is which, so my multiplications at the end are probably way off

use strict; 
use warnings 'all';

my %side = ( i => 24.56, j => 3.56 );

my ($sside, $bside) = $side{i} < $side{j} ? qw/ i j / : qw/ j i /;

$side{$sside} *= 20;
$side{$bside} *= 21;

If you prefer, you could use sort instead to order the hash keys. The result is identical

my ($sside, $bside) = sort { $side{$a} <=> $side{$b} } keys %side;