with data file roads.dat#!/usr/bin/perl -w use strict; use Data::Dumper; @ARGV = 'roads.dat'; my (@lines,@edge,%verts); while(<>){ chomp; push @lines, [split ",", $_]; } map push(@edge, load(@{$_})), @lines; foreach my $edge(@edge){ my($from,$to)=($verts{$edge->{From}},$verts{$edge->{To}}); push @{$from->{Edges}}, $edge; push @{$to->{Edges}}, $edge; print map "$_->{Cost} " , @{$verts{"East Jordan"}->{Edges}}; #print ${$edge}{To}; ${$to}{Cost}=${$from}{Cost}=99999999; } push my @queue, $verts{"East Jordan"}; ${$verts{"Ellsworth"}}{Cost}=0; while(@queue ne 0){ my $town = shift @queue; my $cost = $town->{Cost}; print " | "; print map "$_->{Cost} ", @{$verts{$town}->{Edges}}; foreach(@{$verts{$town}->{Edges}}){ print"[runs]"; my $other = $verts{opposite($_,$town)}; if($cost+$_->{Cost} < $other->{Cost}){ $other->{Cost}=$cost+$_->{Cost}; $other->{Last}=$_; push @queue, $other; } } } print map "$_->{Name} $_->{Cost} $_->{From} $_->{To}\n", @edge; print Dumper(\%verts,\@edge); sub opposite{ if($verts{${$_[0]}{From}} eq $_[1]){ $_[0]->{To}; } elsif ($verts{$_[0]->{To}} eq $_[1]){ $_[0]->{From}; } else { die "opposite failed, ",$!; } } sub load{ {Name => $_[0], Cost => $_[1], From => "$_[2]", To => "$_[3]",}; }
A,5,Ellsworth,East Jordan C,12,Ellsworth,Bellaire B,30,Bellaire,East Jordan D,19,East Jordan,Charleviox E,45,Ellsworth,Elk Rapids F,22,East Jordan,Elk Rapids G,2,East Jordan,Atwood H,14,Atwood,Charleviox
This outputs 12 12 30 12 30 12 30 12 30 12 30 12 30 |
Where if I replace East Jordan with Bellaire, it will print out: 12 12 30 12 30 12 30 12 30 12 30 12 30 | 12 30 runs
And so, if the two strings match, it runs fine, but if they don't, it stops short. But it should work for any string in the data file. What is going on. BTW I'm using 5.8.8 FURTHER UPDATES: print Dumper(\%verts,\@edge); ouputs the following,which makes me wonder why East Jordan never got edge A, as well as how sharing might work in the future.$VAR1 = { 'HASH(0x9f646ec)' => { 'Edges' => [] }, 'Ellsworth' => { 'Cost' => 0 }, 'East Jordan' => { 'Cost' => 99999999, 'Edges' => [ { 'To' => 'East Jordan', 'Cost' => '30', 'Name' => 'B', 'From' => 'Bellaire' }, { 'To' => 'Charleviox', 'Cost' => '19', 'Name' => 'D', 'From' => 'East Jordan' }, { 'To' => 'Elk Rapids', 'Cost' => '22', 'Name' => 'F', 'From' => 'East Jordan' }, { 'To' => 'Atwood', 'Cost' => '2', 'Name' => 'G', 'From' => 'East Jordan' } ] } }; $VAR2 = [ { 'To' => 'East Jordan', 'Cost' => '5', 'Name' => 'A', 'From' => 'Ellsworth' }, { 'To' => 'Bellaire', 'Cost' => '12', 'Name' => 'C', 'From' => 'Ellsworth' }, $VAR1->{'East Jordan'}{'Edges'}[0], $VAR1->{'East Jordan'}{'Edges'}[1], { 'To' => 'Elk Rapids', 'Cost' => '45', 'Name' => 'E', 'From' => 'Ellsworth' }, $VAR1->{'East Jordan'}{'Edges'}[2], $VAR1->{'East Jordan'}{'Edges'}[3], { 'To' => 'Charleviox', 'Cost' => '14', 'Name' => 'H', 'From' } ];
In reply to hashref scope by Trotskey
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |