next up previous contents index
Next: Regular Expressions Up: Comparisons Previous: String comparison   Contents   Index


As well as their use in conditionals, the various constructions for comparing variables also find a use in the sort function, which is used to sort a list. The default behaviour is to sort by string comparison; for example
  my @names = qw(Jennifer Wanda Sally);
  my @sorted_names = sort @names;
  print qq{The sorted array is @sorted_names\n};
will print out
The sorted array is Jennifer Sally Wanda
which is probably what is wanted (ie, sorted alphebatically). However,
  my @numbers;
  for my $index (1 .. 10) {
    $numbers[$index] = int(rand 2000);
  my @sorted_list = sort @numbers;
  print qq{The sorted array is @sorted_list\n};
might print out (for some run)
  The sorted array is  1341 1371 1467 1479 1679 1728 196 1968 678 81
Note that this is in a string-wise, not numerical, order. To put these into numerical order, we have to tell sort to sort things numerically; this can be done via
  my @sorted_list = sort {$a <=> $b} @numbers;
which specifies a routine to use to do the sort. The special variables $a and $b are constructed by Perl from the given list.