Click to See Complete Forum and Search --> : subroutine as an argument


StuPeas
08-22-2006, 06:41 PM
I know this is a real pain, but could someone put me straight on the code below.


sub sort_by_num
{
return $a <=> $b;
}

@arr = (500,1,400,5);

foreach (sort sort_by_num(@arr))
{
print ("$_\n");
}


From what i can figure out, the return value of sort_by_num should be 1,5,400,500. The problem I have is i have never come across a foreach loop with a subroutine in it. Im guessing that when the foreach loop is started the expression in the parentheses is evaluated first. This would result in the foreach loop effectively saying....foreach (sort 1,5,400,500), but since "sort's" default is to sort by ASCII , this would result in the foreach loop being evaluated as this....foreach (1,400,5,500)..., so the print function should result in this
1
400
5
500
but needless to say, i doesnt.

I THINK MY HEAD MY EXPLODE!!!!!!

As always with me, this is a learning thing,and although grateful im not looking for better code that does the same thing, The answer to this will probably teach me something.

TIA

NogDog
08-22-2006, 08:58 PM
I think you just want:

foreach (sort sort_by_num @arr)

StuPeas
08-24-2006, 05:01 AM
I made a miskake and ran this code. I believe it may help to figure out the exact sequence of events taking place from the time the sort function starts to be executed.


sub sort_by_num
{
$i++;
return $a <=> $b;
}

$i=0;
@arr = (500,1,400,5);

foreach (sort sort_by_num(@arr))
{
print "$_\n;";

}

print "i = $i";

The output is
1
;5
;400
;500
;i=5


If possible could you explain each stage in the program for me. I know its alot to ask, but ive been driven mad by this problem for 4 days now, and my course tutors are absolutely useless.

I would be very very grateful.

THANX
Stu