Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tsort: pairs can split across lines #759

Merged
merged 1 commit into from
Oct 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 21 additions & 16 deletions bin/tsort
Original file line number Diff line number Diff line change
Expand Up @@ -49,27 +49,28 @@ if ($file eq '-') {
my %pairs; # all pairs ($l, $r)
my %npred; # number of predecessors
my %succ; # list of successors
my @input;

while (<$fh>) {
next unless m/\w/;
s/\A\s+//;
s/\s+\z//;
my @l = split;
next unless scalar(@l);

if (scalar(@l) % 2 == 1) {
warn "$Program: odd number of tokens on line $.\n";
exit EX_FAILURE;
}
while (@l) {
my $l = shift @l;
my $r = shift @l;
next if defined $pairs{$l}{$r};
$pairs{$l}{$r}++;
$npred{$l} += 0;
++$npred{$r};
push @{$succ{$l}}, $r;
}
push @input, @l if scalar(@l);
}
if (scalar(@input) % 2 == 1) {
warn "$Program: odd number of tokens\n";
exit EX_FAILURE;
}
while (@input) {
my $l = shift @input;
my $r = shift @input;
next if defined $pairs{$l}{$r};
$pairs{$l}{$r}++;
$npred{$l} += 0;
++$npred{$r};
push @{$succ{$l}}, $r;
}
close $fh;

# create a list of nodes without predecessors
my @list = grep {!$npred{$_}} keys %npred;
Expand All @@ -88,6 +89,10 @@ while (@list) {
}

warn "$Program: cycle detected\n" if grep {$npred{$_}} keys %npred;
unless (close $fh) {
warn "$Program: failed to close input: $!\n";
exit EX_FAILURE;
}
exit EX_SUCCESS;

sub usage {
Expand Down
Loading