Using Perl, how can I sort an array using the value of a number inside each array element?

前端 未结 4 1225
离开以前
离开以前 2020-12-17 04:53

Let\'s say I have an array, @theArr, which holds 1,000 or so elements such as the following:

01  \'12 16 sj.1012804p1012831.93.gz\'
02  \'12 16 sj.1012832p10         


        
4条回答
  •  甜味超标
    2020-12-17 05:19

    Yes. The sort function takes an optional comparison function which will be used to compare two elements. It can take the form of either a block of code, or the name of a function to call.

    There is an example at the linked document that is similar to what you want to do:

    # inefficiently sort by descending numeric compare using
    # the first integer after the first = sign, or the
    # whole record case-insensitively otherwise
    
    @new = sort {
    ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0]
                ||
                uc($a)  cmp  uc($b)
    } @old;
    

提交回复
热议问题