1

i have strings inside an array in this way

/hello/Stack/oveflow 14
/hello/Stack/oveflow 11
/hello/Stack/oveflow 12
/hello/Stack/oveflow 166
/hello/Stack/oveflow 1
/hello/Stack/oveflow 2
/hello/Stack/oveflow 5

i have to sort by the last number

is it possible to use sort to do that?

m0skit0
  • 25,268
  • 11
  • 79
  • 127
Yokupoku Maioku
  • 493
  • 7
  • 21

1 Answers1

6

Yes, sort is exactly what you need. Just provide the code block to compare two elements:

my @sorted = sort { ($a =~ /[0-9]+/g)[-1]
                    <=>
                    ($b =~ /[0-9]+/g)[-1]
                  } @array;

<=> does the numeric comparison. The matching returns all the numbers in the string, [-1] selects the last one.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • thanks a lot, sort can't be used for the given array, i mean,it always create a new array sorted? – Yokupoku Maioku Nov 07 '14 at 12:43
  • 1
    @YokupokuMaioku: For `@array = sort { ...} @array;`, Perl does the in-place sort. See http://stackoverflow.com/q/5163064/1030675 – choroba Nov 07 '14 at 12:44
  • 2
    Also note. If you do some transformation with the data. In this case running a regex on $a and $b, it can make sense to use the [Schwartzian Transformation](http://stackoverflow.com/questions/6483475/schwartzian-transform-in-perl) for performance – David Raab Nov 07 '14 at 13:27