Array Sort in Perl

I am new to Perl and adhered to the (probably simple) task of sorting an array.

I inherited some Perl code that reads lines from a text file into three 1-D arrays (x, y, z). I would like to be able to sort these arrays using one of the parameters as a key and reordering the other two dimensions.

For example, if my input is:

  • @x = (1, 3, 2)
  • @y = (11,13,12)
  • @z = (21,23,22)

and I sort by x, I would like the result to be:

  • @x = (1, 2, 3)
  • @y = (11,12,13)
  • @z = (21,22,23)

I could combine three one-dimensional arrays into a 2-dimensional array if this makes life easier.

+5
source share
6 answers
use strict;
use warnings;
use Data::Dumper;

use List::Util qw(reduce);

my @x = (1, 3, 2);
my @y = (11, 13, 12);
my @z = (21, 23, 22);

my @combined = map { [ $x[$_], $y[$_], $z[$_] ] } 0 .. $#x;
my @sorted = sort { $a->[0] <=> $b->[0] } @combined;
my $split_ref = reduce { push @{$a->[$_]}, $b->[$_] for 0 .. $#$a; $a;} [[], [], []], @sorted;

print Dumper \@combined;
print Dumper \@sorted;
print Dumper $split_ref;

Which essentially will give you:

    [
      [
        1,
        2,
        3
      ],
      [
        11,
        12,
        13
      ],
      [
        21,
        22,
        23
      ]
    ];
+3
source

. sort, @x:

@sort_by_x = sort { $x[$a] <=> $x[$b] } 0 .. $#x;    #   ==> (0, 2, 1)

:

@x = @x[@sort_by_x];
@y = @y[@sort_by_x];
@z = @z[@sort_by_x];
+10

.

@sorted = sort { $a->[0] <=> $b->[0] } 
    ( [$x[0], $y[0], $z[0]], [$x[1], $y[1], $z[1]], [$x[2], $y[2], $z[2]] );

. , , !

0

@x , @y @z, - !

use strict;
use warnings;
use 5.010;

my @x = (1, 3, 2);
my @y = (11,13,12);
my @z = (21,23,22);

say join ', ', @y;
@y = @y[ map { $_ - 1 } @x ]; #We use map create a lists of the values of elements in @x, minus 1.
say join ', ', @y;

, , @x :

@y = sort { $a <=> $b } @y;

, , a , ala

my @indexes = map { $_ - 1 } @x;

for my $array_ref ( \@x, \@y, \@z ) {
    @$array_ref = @{$array_ref}[@indexes];
}
0

:

#!/usr/bin/perl 
use 5.10.1;
use strict;
use warnings;
use Data::Dumper;

my @x = (1, 3, 2);
my @y = (11,13,12);
my @z = (21,23,22);

my (%y, %z);

@y{@x} = @y;
@z{@x} = @z;

my @xs = sort @x;
my @ys = @y{@xs};
my @zs = @z{@xs};
say Dumper \@xs,\@ys,\@zs;

:

$VAR1 = [
          1,
          2,
          3
        ];
$VAR2 = [
          11,
          12,
          13
        ];
$VAR3 = [
          21,
          22,
          23
        ];
0

Do

@a = sort { $a <=> $b } @a;

. perldoc.

-1

All Articles