Sort array using sort and sort_by



examples/other/sort_by.pl
use strict;
use warnings;

use List::UtilsBy qw(sort_by);

my @numbers = (2, -3, 4);
my @sorted = sort @numbers;
print "@sorted\n";

@sorted = sort { abs($a) <=> abs($b) } @numbers;
print "@sorted\n";

@sorted = sort_by { abs($_) }  @numbers;
print "@sorted\n";

examples/other/sort_by_complexity.pl
use strict;
use warnings;

use List::UtilsBy qw(sort_by);

sub func {
    my ($val) = @_;
    print "func $val\n";
    return $val;
}

my @sorted = sort { func($a) <=> func($b) } (4, 3, 2, 1);
print "@sorted\n";
print "\n";  # looks like func is called n * log(n)

@sorted = sort_by { func($_) } (4, 3, 2, 1);
print "@sorted\n";
print "\n";  # func is only called n times

examples/other/sort_by_planets.pl
use strict;
use warnings;

use Text::CSV qw(csv);
use Data::Dumper qw(Dumper);
use List::UtilsBy qw(sort_by);

my $filename = 'planets.csv';
my $solar_system = csv(
    in => $filename,
    headers => 'auto');

#print Dumper $solar_system;

#my @sorted = sort_by { $_->{'Planet name'} }  @$solar_system;
my @sorted = sort_by { $_->{'Mass'} }  @$solar_system;
print Dumper \@sorted;

my @sorted  = sort { $a->{'Planet name'} cmp $b->{'Planet name'} }
    @$solar_system;