Re: missing curly - brain fried
- From: tom@xxxxxxxxxxxxxx (Tom Phoenix)
- Date: Thu, 28 Jun 2007 08:25:12 -0700
On 6/28/07, Amichai Teumim <amichai@xxxxxxxxxx> 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
.
- References:
- missing curly - brain fried
- From: Amichai Teumim
- missing curly - brain fried
- Prev by Date: Re: printing content of found file
- Next by Date: Re: don't understand working script
- Previous by thread: Re: missing curly - brain fried
- Next by thread: Adding a line in a file inside many directories
- Index(es):
Relevant Pages
|
|