Your interpretation of the first run through the first loop is correct, but only because your first element is the largest. It might help if you have some proper indenting of your code:
- my @arr1=(5,3,2,1,4);
-
my $i=0;
-
my $j=0;
-
$tmpnum # should be my $tmpnum;
-
for($i=0;$i<@arr1;$i++) {
-
for($j=0;$j<@arr1;$j++) {
-
if($arr1[$i]<$arr1[$j]) {
-
$tmpnum=$arr1[$i];
-
$arr1[$i]=$arr1[$j]
-
$arr1[$j]=$tmpnum;
-
};
-
};
-
};
-
-
foreach(@arr1) {
-
print $_ . "\n";
-
}
Ahh, much better and easier to read! Now, about those loops:
We enter loop 1: $i is 0.
We enter loop 2: $j is 0.
Is $arr1[$i] < $arr1[$j]? Well, $i = 0, $j = 0, $arr1[0] = 5, and 5 is not less than 5. So the if statement is not executed. We skip past the if statement.
Exit loop 2. We increment $j to 1.
Is $j < @arr1? $j = 1, @arr1 = 5, 1 < 5, so the loop goes again. Enter loop 2.
Is $arr1[$i] < $arr1[$j]? Well, $i = 0, $j = 1, $arr1[0] = 5, $arr[1] = 3, and 5 is not less than 5. So the if statement is not executed. We skip past the if statement.
(blah blah blah, until...)
We increment $j to 5.
Is $j < @arr1? $j = 5, @arr1 = 5, and 5 is not less than 5, so we no longer execute loop 2.
Exit loop 1. Increment $i to 1. Check: is $1 < @arr1? Yes, because 1 < 5. Enter loop 1.
Enter loop 2: $j = 0 again! Not 1!
Is $arr1[$i] < $arr1[$j]? Well, $i = 1, $j = 0, $arr1[1] = 3, $arr1[0] = 5, and 3 < 5! So the if statement executes!
The if statement swaps the two values, making @arr1 contain (3,5,2,1,4).
Exit loop 2. We increment $j to 1.
(blah blah blah)
Hopefully that explains the nested loops in this circumstance a little better.