# This is the overall route
-my $route = get_stops( $url );
+my $route = get_stops( $url, 1 );
# Add the overall route to the journeys list, otherwise if it's cheapest the
# summary doesn't have its details.
}
printf "Total price: £%.2f\n", $sum;
printf "Direct price: £%.2f\n", $route->{price};
+my $saving = $route->{price} - $sum;
+my $percent = 100 * $saving / $route->{price};
+printf "Saving: £%d (%.f%%)\n", $saving, $percent;
printf "[calculated in %ds]\n", ( time - $timer );
##
## functions below here
# Get ticket price, type and stops from a URL
sub get_stops {
- my ( $url ) = @_;
+ my ( $url, $full_journey ) = @_;
debug( "get_stops( $url )" );
$mech->get( $url );
my $tree = HTML::TreeBuilder->new_from_content( $mech->content );
- my $first_stop = $tree->look_down( '_tag', 'li', 'id', 'result0' );
+ my $stop_li;
+ foreach my $entry ( $tree->look_down('_tag', 'ul', 'class', 'results')->look_down('_tag', 'li') ){
+ my ( $dep ) = $entry->look_down('_tag', 'strong')->as_text =~ m{^\s*(\d+:\d+)\s};
+ # If it's the full journey (ie finding the route based on a
+ # user-supplied time) be a little more flexible, take the first result.
+ if( $full_journey or ( $dep eq ( split( m{/}, $url ) )[5] ) ){
+ $stop_li = $entry;
+ last;
+ }
+ }
+ unless( $stop_li ){
+ die "Cannot find any train leaving at the requested time from $url";
+ }
# check if it's direct or not:
- my $change_link = $first_stop->look_down('_tag', 'a', 'class', 'change_link');
+ my $change_link = $stop_li->look_down('_tag', 'a', 'class', 'change_link');
if( $change_link ){
die "Error: first train returned by $url is not direct!\n";
}
- my $details_url = $first_stop->look_down( '_tag', 'a', 'class', 'calling_link' )->attr('href');
- my $ticket_type = $first_stop->look_down( '_tag', 'span', 'class', 'fare-type tooltip')->look_down('_tag', 'a')->as_text;
- my $ticket_price = ( $first_stop->look_down( '_tag', 'label' ) )[0]->as_text;
+ my $details_url = $stop_li->look_down( '_tag', 'a', 'class', 'calling_link' )->attr('href');
+ my $ticket_type = $stop_li->look_down( '_tag', 'span', 'class', 'fare-type tooltip')->look_down('_tag', 'a')->as_text;
+ my $ticket_price = ( $stop_li->look_down( '_tag', 'label' ) )[0]->as_text;
$tree = $tree->delete();