-4

I have read a lot of guides, maybe I just don't get it.

I have a string and converted it to an array. Now I need to arrange its content in a descending order based on the last column. Here is how my array looks like in a "string view":

   @array = [

   Machine1, 01/02/2016, 02/01/2016, 26

   Machine2, 02/01/2016, 02/01/2016, 1

   Machine3, 02/01/2016, 02/01/2016, 78

   ]

In this array, the whole "Machine1, 01/02/2016, 02/01/2016, 26" is considered a whole string in an array, and based last column (which I consider) which is: 26, 1, 78 <- I wish I could order then in a descending order: 78, 26, 1.

Sorry for the childish question.

Thanks in advance.

felipsmartins
  • 13,269
  • 4
  • 48
  • 56
Demonic_Dog
  • 142
  • 1
  • 9

3 Answers3

2

It's not ideal to start with an array of strings when an array of arrays would be better, but we can work with that by split-ing each string into its component parts. Then we just sort on the element you're interested in, and Bob's your uncle.

use strict;
use warnings;

use Data::Dump;

my @array = (
    'Machine1, 01/02/2016, 02/01/2016, 26',
    'Machine2, 02/01/2016, 02/01/2016, 1',
    'Machine3, 02/01/2016, 02/01/2016, 78',
);

@array = sort { $b->[3] <=> $a->[3] }
         map  { [ split(/,\s*/) ] }
         @array;

dd(\@array);

Output:

[
  ["Machine3", "02/01/2016", "02/01/2016", 78],
  ["Machine1", "01/02/2016", "02/01/2016", 26],
  ["Machine2", "02/01/2016", "02/01/2016", 1],
]

If you need to keep the data in the original format, you can use a Schwartzian transform:

@array = map  { $_->[0] }
         sort { $b->[1] <=> $a->[1] }
         map  { [ $_, (split(/,\s*/))[3] ] }
         @array;

Result:

[
  "Machine3, 02/01/2016, 02/01/2016, 78",
  "Machine1, 01/02/2016, 02/01/2016, 26",
  "Machine2, 02/01/2016, 02/01/2016, 1",
]
Community
  • 1
  • 1
Matt Jacob
  • 6,503
  • 2
  • 24
  • 27
1

Reverse each string, sort as desired (descending), reverse them back.

use warnings;
use strict;

my @array = (   
    'Machine1, 01/02/2016, 02/01/2016, 26', 
    'Machine2, 02/01/2016, 02/01/2016, 1',
    'Machine3, 02/01/2016, 02/01/2016, 78'
);

my @sorted = map { my $s = reverse; $s }
             sort { $b cmp $a } 
             map { my $s = reverse; $s }  @array;

print "$_\n" for @sorted;

This prints

Machine3, 02/01/2016, 02/01/2016, 78
Machine1, 01/02/2016, 02/01/2016, 26
Machine2, 02/01/2016, 02/01/2016, 1
zdim
  • 64,580
  • 5
  • 52
  • 81
-2

Use Schwartzian Transformation ( google Schwarzian Transformation in perl )

Done by creating a new array {index,string} , sorting on index, but printing out only string ( without any further processing ).

Arif Burhan
  • 507
  • 4
  • 12