Skip to content

Commit

Permalink
tsort: raise error for odd input tokens
Browse files Browse the repository at this point in the history
* The input "a" by itself results in a fatal error for BSD and GNU versions
* Previously this version ignored odd arguments, but that is contrary to the standard [1]
* Also, the standard does not stipulate that each line contains only one pair
* When reading source code of OpenBSD version I discovered the input "a b b c b d d f c e" on one line is treated the same as for pairs on separate lines (GNU tsort behaves the same here)
* Accept multiple pairs per line for better compatibility, and remove the mention of the old limitation in the POD

1. https://pubs.opengroup.org/onlinepubs/9699919799/utilities/tsort.html
  • Loading branch information
mknos authored Oct 10, 2024
1 parent b6e4ec7 commit 1fec11e
Showing 1 changed file with 18 additions and 14 deletions.
32 changes: 18 additions & 14 deletions bin/tsort
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ License: perl
=cut


use strict;

use File::Basename qw(basename);
Expand Down Expand Up @@ -52,13 +51,23 @@ my %npred; # number of predecessors
my %succ; # list of successors

while (<$fh>) {
my ($l, $r) = my @l = split;
next unless @l == 2;
next if defined $pairs{$l}{$r};
$pairs{$l}{$r}++;
$npred {$l} += 0;
++$npred{$r};
push @{$succ{$l}}, $r;
next unless m/\w/;
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;
}
}
close $fh;

Expand Down Expand Up @@ -118,15 +127,10 @@ breadth-first or depth-first (default) traversal
=item B<filename>
Optional input file.
Input format is pairs of white-space-separated fields,
one pair per line.
Input format is pairs of white-space-separated fields.
Each field is the name of a node.
Output is the topologically sorted list of nodes.
Ignores lines without at least two fields.
Ignores all fields on the line except the first two.
=back
=head1 AUTHOR
Expand Down

0 comments on commit 1fec11e

Please sign in to comment.