in reply to Re: Advise on sql table mapping.
in thread Advise on sql table mapping.

I have been playing with the code you posted above. It's outputting the correct data but I am not sure why i am seeing some warnings and a few blank line.

Modified:

#!/usr/bin/perl -w my @links = map { [/^(\w+)\s+(\w+)/] } split /\n/, <<LINKS; apple bug unid1 unid2 apple cat unid1 unid3 bug dog unid2 unid4 apple dog unid1 unid4 dog owl unid4 unid5 LINKS # All links work both ways: my %links; for (@links) { my ($left,$right) = @$_; # We store all links in arrays $links{$left} ||= []; $links{$right} ||= []; # Links work both ways push @{$links{$left}}, $right; push @{$links{$right}}, $left; } sub find_joins { my ($start, $goal, $prefix, $visited) = @_; $visited ||= {}; # our breadcrumb trail so we dont $prefix ||= []; # the path so far my $curr = $start; # warn "[@$prefix] $start => $goal"; my @results; # All the paths that lead from $start to $end $visited->{$start} = 1; for my $link (grep { ! $visited->{$_} } @{$links{$start}}) { if ($link eq $goal) { push @results, [@$prefix,$start,$goal]; } else { my %v = %$visited; push @results, find_joins($link,$goal,[@$prefix,$start],\% +v); } } # Sort by length, then asciibetically @results = sort { scalar @$a <=> scalar @$b or $a->[0] cmp $b->[0] + } @results; # print the whole thing with indices for $i ( 0 .. $#results ) { print "@{$results[$i]}\n"; } } find_joins( 'apple' => 'owl' );
Output:
dbmathis@dbmathis-linux:~$ ./tmp.pl apple bug dog owl apple dog owl Use of uninitialized value in string comparison (cmp) at ./tmp.pl line + 46. Use of uninitialized value in string comparison (cmp) at ./tmp.pl line + 46. dbmathis@dbmathis-linux:~$
After all this is over, all that will really have mattered is how we treated each other.

Replies are listed 'Best First'.
Re^3: Advise on sql table mapping.
by Corion (Patriarch) on May 19, 2008 at 19:56 UTC

    The print statements will also try out to print stuff when no path can be found. You shouldn't print out stuff within find_joins, you should print out the results of the top-level call to it. Leaving the warn statement active would have helped you see the flow of control better.

    Why did you remove the use strict; line? Adding it again points to a potential error.

      I had removed strict and forgot to add it back when I was calling @results from outside the loop.

      Just basically studying your code. Thanks btw. This has really helped me greatly.

      After all this is over, all that will really have mattered is how we treated each other.

        I'm not sure what you mean by "calling @results from outside the loop", but if you mean what I think you mean, you might benefit from Coping With Scoping. @results is not visible anymore once find_joins has finished running. Use the return value(s) of find_joins, like I did.