Last active
July 24, 2020 16:39
-
-
Save LadyAleena/876dd80e69eb3f2ab84aa4fdba105516 to your computer and use it in GitHub Desktop.
A module to return a list sorted by split values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Fancy::Sort::Split; | |
use v5.8.8; | |
use strict; | |
use warnings FATAL => qw( all ); | |
use Exporter qw(import); | |
our $VERSION = '1.0'; | |
our @EXPORT_OK = qw(split_sort); | |
sub split_sort { | |
my ($in_a, $in_b, $split, $sort_type) = @_; | |
$split = qr($split); | |
my ($numa1, $numa2) = split(/$split/, $in_a); | |
my ($numb1, $numb2) = split(/$split/, $in_b); | |
if ($sort_type =~ /^num/) { | |
$numa1 <=> $numb1 || $numa2 <=> $numb2 | |
} | |
elsif ($sort_type =~ /^(alpha|letter)/) { | |
$numa1 cmp $numb1 || $numa2 cmp $numb2 | |
} | |
} | |
=pod | |
=encoding utf8 | |
=head1 NAME | |
B<Fancy::Sort::Split> returns the expression to split the values in lists for L<sort|https://perldoc.perl.org/functions/sort.html> subroutines. | |
=head1 VERSION | |
This document describes Fancy::Sort::Split version 1.0. | |
=head1 SYNOPSIS | |
my @numbers = qw(1_2 1_02 3_4 5_78 50_89); | |
my @sorted = sort @numbers; | |
# returns | |
# [ | |
# '1_02', | |
# '1_2', | |
# '3_4', | |
# '50_89', | |
# '5_78' | |
# ] | |
my @split_sorted = sort { split_sort($a, $b, '_', 'number') } @numbers; | |
# returns | |
# [ | |
# '1_2', | |
# '1_02', | |
# '3_4', | |
# '5_78', | |
# '50_89' | |
# ]; | |
=head1 DESCRIPTION | |
Fancy::Sort::Split returns the expression to split the values in lists for L<sort|https://perldoc.perl.org/functions/sort.html> subroutines. The subroutine C<split_sort> has found required parameters. | |
The first and second paremeters are C<$a> and C<$b> from C<sort>. The third parameter is the character or string you want to split the strings by. The fourth is the type of sort you want, C<number> or C<alpha> (C<letter>). | |
=head2 Numerical sort | |
split_sort($a, $b, 'char', 'number'); | |
A note of caution, when a number has a leading zero (02), the leading zero will be dropped. So, C<02> will be the same as C<2>. | |
=head2 Alphabetical sort | |
split_sort($a, $b, 'char', 'alpha'); | |
split_sort($a, $b, 'char', 'letter'); | |
=head1 DEPENDENCIES | |
Fancy::Sort::Split depends on L<Exporter>. | |
=head1 AUTHOR | |
Lady Aleena | |
=cut | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment