On 6/28/07, Amichai Teumim <[EMAIL PROTECTED]> wrote:
Where is the open curly missing here?
Here it is:
@array = sort { $a <=> $b } @array;
But if you really want to do it the hard, slow way.... Well, then you
should be programming this as a shell script. But let's at least
translate your code to Perl.
#!/usr/bin/perl
use strict;
use warnings;
@array = (5,3,2,1,4);
Declare most new variables with my().
my @array = (5, 3, 2, 1, 4);
for ($i=0; $i<$n-1; $i++) {
( for ($j=0; $j<$n-1-$i; $j++)
The curly braces of a block are never optional in Perl, unlike in C.
Most uses of the C-style computed for loop are simpler as a foreach
loop in Perl:
for my $i (0..$#array-1) {
for my $j (0..$#array-1-$i) {
if ($array[$j+1] < $array[$j]) { /* compare the two neighbors
*/
$tmp = $array[$j]; /* swap $array[j] and $array[j+1]
*/
$array[$j] = $array[$j+1];
$array[$j+1] = $tmp;
}
}
Perl doesn't have multi-line comments like C, and it doesn't need to
use temp variables to swap two items.
# compare two neighbors
if ($array[$j+1] < $array[$j]) {
# swap these two
($array[$j], $array[$j+1]) = ($array[$j+1], $array[$j]);
}
# end two nested loops
}
}
foreach $elem (@array){
print "$elem";
}
print "Results: @array\n";
But I like the one liner better, perhaps because I have more
confidence in its algorithm. Hope this helps!
--Tom Phoenix
Stonehenge Perl Training
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/