Tobias Eichner wrote: > > I'm currently dealing with a sample program I try to understand. Here it is: > > --- > > #!/usr/bin/perl > > use strict; use warnings; use diagnostics; > > # Array to sort > my @unsortiert = qw(Z A z a 19 91); > > # Print array to sort > print "@unsortiert"; print "\n"; > > # Print positions of unsorted array (0 to last entry #) > my @pos_unsortiert = (0..$#unsortiert); > print "@pos_unsortiert"; print "\n"; > > # Start sorting > my @pos_sortiert = sort({"$unsortiert[$a]" cmp "$unsortiert[$b]"} > (0..$#unsortiert)); > > print "@pos_sortiert"; print "\n"; > > my @sortiert; > for (0..$#unsortiert) > { > $sortiert[$_] = $unsortiert[$pos_sortiert[$_]]; > print "\n$unsortiert[$_] was element $_\t\tand is now element > $pos_sortiert[$_]."; > }; > print "\n\nThis is the sorted result: @sortiert"; print "\n"; > > --- > > For unknown reason sorting fails when running the program using an array that > contains numbers. I'm aware that I try here to compare numbers with the cmp > operator, but although warnings have be enabled, Perl doesn't get angry > about. > > So when you run this script as above, you'll notice that the sorting is done > correctly, but the positions aren't. More strangly when sorting an array of > strings only, anything is correct (soring and positions output). > > Maybe some of you can give me a hint, since I want to understand why it > doesn't work when using numbers ?
If you were using the <=> operator to compare non-numeric strings you would get a warning, but any scalar value is a valid string so you will get no warnings if you compare numeric values with the cmp operator. Sorting numbers as strings causes them to be sorted in dictionary order, which is different from numeric order if the numbers have the same number of digits. So 2 is greater than 11 in the same way that 'B'is greater than 'AA'. I'm not clear what you mean by "the sorting is done correctly, but the positions aren't", but I hope that helps? Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/