Skip to content

Commit

Permalink
tsort: pairs can split across lines (#759)
Browse files Browse the repository at this point in the history
* The previous commit handled the problem of odd input tokens being ignored, but tsort still rejects some valid input
* Exit with failure code if close() failed, after printing output
* Allow a single token on a line; this is valid as long as the total number of tokens is even
* Tested against GNU version

%printf "a b\nb\n  c\n\n" > in.tsort
%tsort in.tsort # tsort (GNU coreutils) 8.32
a
b
c
%perl tsort in.tsort # with patch applied
a
b
c
%perl ~/PerlPowerTools.old/bin/tsort in.tsort # from older commit 9d4efce which gets it totally wrong
a
b
  • Loading branch information
mknos authored Oct 15, 2024
1 parent 14732c1 commit 59942ec
Showing 1 changed file with 21 additions and 16 deletions.
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

0 comments on commit 59942ec

Please sign in to comment.