Re: missing curly - brain fried



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
.



Relevant Pages

  • Re: Need help understanding how a file input block works
    ... here is a section of the Perl code that I am having ... ^ says 'match if we are at the start of the string', ... 'next' is documented in perldoc perl, in the sextion "Loop Control". ... which will stop you from using globals by accident. ...
    (comp.lang.perl.misc)
  • Re: perl newbie: leaner code ideas
    ... > To learn Perl, I have written a bit of code that needs to do the following: ... Don't declare variables prematurely. ... if the foreach loop contriol variable has already been ... variable as a foreach loop contriol variable without an explicit "my". ...
    (comp.lang.perl)
  • Re: Noob! Help required and would be really appreciated!
    ... You've read 60% of "Learning Perl"? ... On finding the keyword "New Order", it has to start building a hash. ... want to build a loop around this hash creation. ... transferred to %allOrders. ...
    (comp.lang.perl.misc)
  • Re: Perl and Python, a practical side-by-side example.
    ... suggest a few minor edits to the Perl version. ... list then it's better to declare the variable directly in the loop ... for my $piid ){ ... #If the current record is the correct state ...
    (perl.beginners)
  • RE: Big Problem, Load Avg Very High
    ... I disabled one of my clients web pages (the one that gets the most hits ... 500MB of swap used? ...
    (freebsd-questions)