First Perl Question - about sorting numeric arrays

B

BKennedy

Hello,

Well here goes my first newbie PERL question for the gurus of this
group. My issue is with using the SORT instruction. Below you'll
find the printed contents of 5 element array before and after a
'sorting'. Is the 'sorting' being performed on the references and not
the contents? I don't understand why the numbers are sometimes not in
proper sequence after the SORT. (Shouldn't the second printing of the
first array read : 5 9 13 13 14 ?)

for $a(0..3)
{
for($i=0;$i<5;$i++)
{
$array[$i] = int(rand(19) +1);
}
print("$a\t @array \n");
@array = sort @array;
print("$a\t @array \n");
}

Results:
0 14 13 13 9 5
0 13 13 14 5 9
1 11 10 5 12 15
1 10 11 12 15 5
2 8 16 7 14 13
2 13 14 16 7 8
3 12 6 12 5 4
3 12 12 4 5 6

Any help is appreciated. Thanks.

-Bkennedy
 
J

Jack D.

BKennedy said:
Hello,

Well here goes my first newbie PERL question for the gurus of this
group. My issue is with using the SORT instruction. Below you'll
find the printed contents of 5 element array before and after a
'sorting'. Is the 'sorting' being performed on the references and not
the contents? I don't understand why the numbers are sometimes not in
proper sequence after the SORT. (Shouldn't the second printing of the
first array read : 5 9 13 13 14 ?)

for $a(0..3)
{
for($i=0;$i<5;$i++)
{
$array[$i] = int(rand(19) +1);
}
print("$a\t @array \n");

Stop right here. Read:

perldoc -q sort

before you write your next line.
 
S

Sam Holden

Hello,

Well here goes my first newbie PERL question for the gurus of this
group. My issue is with using the SORT instruction. Below you'll
find the printed contents of 5 element array before and after a
'sorting'. Is the 'sorting' being performed on the references and not
the contents? I don't understand why the numbers are sometimes not in
proper sequence after the SORT. (Shouldn't the second printing of the
first array read : 5 9 13 13 14 ?)

No because you are doing a string sort and the string "5" comes
later than the string "13" when sorted into dictionary order,
just like "e" comes after "ac".

perldoc -f sort

Provides numerous examples on how to use the sort function,
including sorting numerically.

You should read the posting guileines that are posted here frequently.
It is also available at:
http://mail.augustmail.com/~tadmc/clpmisc/clpmisc_guidelines.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top