xref: /openbsd/gnu/usr.bin/perl/Porting/manisort (revision 5af055cd)
1#!/usr/bin/perl
2
3# Usage:  manisort [-q] [-o outfile] [filename]
4#
5# Without 'filename', looks for MANIFEST in the current dir.
6# With '-o outfile', writes the sorted MANIFEST to the specified file.
7# Prints the result of the sort to stderr.  '-q' silences this.
8# The exit code for the script is the sort result status
9# (i.e., 0 means already sorted properly, 1 means not properly sorted)
10
11use strict;
12use warnings;
13$| = 1;
14
15# Get command line options
16use Getopt::Long;
17my $outfile;
18my $check_only = 0;
19my $quiet = 0;
20GetOptions ('output=s' => \$outfile,
21            'check'    => \$check_only,
22            'quiet'    => \$quiet);
23
24my $file = (@ARGV) ? shift : 'MANIFEST';
25
26# Read in the MANIFEST file
27open(my $IN, '<', $file)
28    or die("Can't read '$file': $!");
29my @manifest = <$IN>;
30close($IN) or die($!);
31chomp(@manifest);
32
33# Sort by dictionary order (ignore-case and
34#   consider whitespace and alphanumeric only)
35my @sorted = sort {
36                      (my $aa = $a) =~ s/[^\s\da-zA-Z]//g;
37                      (my $bb = $b) =~ s/[^\s\da-zA-Z]//g;
38                      uc($aa) cmp uc($bb)
39                  } @manifest;
40
41# Check if the file is sorted or not
42my $exit_code = 0;
43for (my $ii = 0; $ii < $#manifest; $ii++) {
44    next if ($manifest[$ii] eq $sorted[$ii]);
45    $exit_code = 1;   # Not sorted
46    last;
47}
48
49# Output sorted file
50if (defined($outfile)) {
51    open(my $OUT, '>', $outfile)
52        or die("Can't open output file '$outfile': $!");
53    binmode($OUT);
54    print($OUT join("\n", @sorted), "\n");
55    close($OUT) or die($!);
56}
57
58# Report on sort results
59printf(STDERR "'$file' is%s sorted properly\n",
60            (($exit_code) ? ' NOT' : '')) if (! $quiet);
61
62# Exit with the sort results status
63exit($exit_code);
64
65# EOF
66