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
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