aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorE. Choroba <choroba@matfyz.cz>2020-06-07 13:06:30 +0200
committerE. Choroba <choroba@matfyz.cz>2020-06-07 13:06:30 +0200
commit76ef43714d687a1b3d15a1bd5ecb2bb00645463b (patch)
treef127c864cca0f79f26995277c39b600572be8e1b
parent32ff9db36c53197bb8c683519daa0407f4aff026 (diff)
downloadperlweeklychallenge-club-76ef43714d687a1b3d15a1bd5ecb2bb00645463b.tar.gz
perlweeklychallenge-club-76ef43714d687a1b3d15a1bd5ecb2bb00645463b.tar.bz2
perlweeklychallenge-club-76ef43714d687a1b3d15a1bd5ecb2bb00645463b.zip
Solve 062/1 Sort Email Address by E. Choroba
Use Email::Address::XS to correctly parse addresses containing @ and " in the user part.
-rwxr-xr-xchallenge-062/e-choroba/perl5/ch-1.pl72
1 files changed, 72 insertions, 0 deletions
diff --git a/challenge-062/e-choroba/perl5/ch-1.pl b/challenge-062/e-choroba/perl5/ch-1.pl
new file mode 100755
index 0000000000..3c9b2f36a9
--- /dev/null
+++ b/challenge-062/e-choroba/perl5/ch-1.pl
@@ -0,0 +1,72 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use feature qw{ say };
+
+{ package My::Email::Sorter;
+ use Email::Address::XS;
+ use List::UtilsBy qw{ uniq_by };
+
+ sub _sort {
+ sort { lc $a->host cmp lc $b->host
+ || $a->user cmp $b->user
+ } @_
+ }
+
+ sub _parse {
+ map 'Email::Address::XS'->parse($_), @_
+ }
+
+ sub sort_by_domain {
+ return map $_->address, _sort(_parse(@_))
+ }
+
+ sub sort_by_domain_uniq {
+ my @emails = @_;
+ return map $_->address,
+ _sort(
+ uniq_by { join $_->user, '@', lc $_->host }
+ reverse _parse(@_) )
+ }
+}
+
+use Getopt::Long qw( :config no_getopt_compat ); # +u not allowed
+GetOptions(u => \ my $unique);
+
+if ($unique) {
+ say for My::Email::Sorter::sort_by_domain_uniq(<>);
+
+} else {
+ say for My::Email::Sorter::sort_by_domain(<>);
+}
+
+__END__
+use Test::More;
+use Test::Deep;
+
+my @t1 = qw( name@example.org
+ rjt@cpan.org
+ Name@example.org
+ rjt@CPAN.org
+ user@alpha.example.org );
+
+cmp_deeply [My::Email::Sorter::sort_by_domain(@t1)],
+ [qw[ user@alpha.example.org
+ rjt@cpan.org
+ rjt@CPAN.org
+ Name@example.org
+ name@example.org ]];
+
+cmp_deeply [My::Email::Sorter::sort_by_domain_uniq(@t1)],
+ [qw[ user@alpha.example.org
+ rjt@CPAN.org
+ Name@example.org
+ name@example.org ]];
+
+my @t2 = qw( "charlie@home"@email.us
+ "anna\"@\"home"@email.us );
+cmp_deeply [My::Email::Sorter::sort_by_domain(@t2)],
+ [qw[ "anna\"@\"home"@email.us
+ "charlie@home"@email.us ]];
+
+done_testing();