Last active
December 21, 2016 11:29
-
-
Save jadeallenx/f95cfc7ae9fc89020e574fc979faad05 to your computer and use it in GitHub Desktop.
Complete listing for my 2016 Perl Advent article
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
requires 'Text::CSV' | |
requires 'Geo::Calc::XS' | |
requires 'IO::String' |
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
use 5.014; | |
use Text::CSV; | |
use IO::String; | |
use Geo::Calc::XS; | |
use List::Util qw(reduce); | |
my $data =<<_DATA; | |
id, name, nice, siblings, present | |
1, Hermione, 1, 0, Owl food | |
2, Delores, 0, 1, Coal | |
3, Draco, 0, 0, Dirty sock | |
4, Ronald, 1, 6, Scarf | |
_DATA | |
my $fh = IO::String->new($data); | |
my $csv = Text::CSV->new( { allow_whitespace => 1 } ); | |
$csv->column_names( $csv->getline($fh) ); | |
my @nice = grep {; $_->{nice} } @{ $csv->getline_hr_all($fh) }; | |
close $fh; | |
my %locations = ( | |
1 => [41.94757, -87.6562], | |
2 => [34.07905, -118.4744], | |
3 => [30.26759, -97.74299], | |
4 => [21.30485, -157.8578], | |
); | |
my @deliveries = map {; my $loc = $locations{$_->{id}}; | |
$_->{geo} = Geo::Calc::XS->new( lat => $loc->[0], | |
lon => $loc->[1], units => 'mi' ); | |
$_ } @nice; | |
my $miles_traveled = reduce {; $a->{geo}->distance_to( $b->{geo} ) } @deliveries; | |
say $miles_traveled; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Really nice article and code.
But I think that the reduce example is broken if there are more than two locations in
@deliveries
.My suggested changes are at: https://gist.github.com/mjg17/aec4c90919050f5de9b54ba9715164df/revisions
Season's greetings
Michael