Debian Codegraph @

scripts/cg-sort

raw
1 #!/usr/bin/perl
2 # -*- mode: cperl; indent-tabs-mode: nil; tab-width: 3; cperl-indent-level: 3; -*-
3 use warnings;
4 use strict;
5 use utf8;
6 BEGIN {
7 $| = 1;
8 binmode(STDIN, ':encoding(UTF-8)');
9 binmode(STDOUT, ':encoding(UTF-8)');
10 }
11 use open qw( :encoding(UTF-8) :std );
12
13 use Getopt::Long;
14 Getopt::Long::Configure('bundling');
15 Getopt::Long::Configure('no_ignore_case');
16 my %opts = ();
17 GetOptions(\%opts, ('weight|w:s', 'reverse|r', 'first|1', 'help|?'));
18
19 sub print_help {
20 print <<'XOUT';
21 Usage: cg-sort [OPTIONS]
22
23 Pipe a CG stream through this to sort and unique the readings of each cohort.
24
25 Options:
26 -?, --help outputs this help
27 -w, --weight sorts by a numeric tag; defaults to W
28 -r, --reverse reverses the sort order
29 -1, --first only keep the first reading
30
31 XOUT
32 }
33
34 if (defined $opts{'help'}) {
35 print_help();
36 exit(0);
37 }
38
39 my $W = 'W';
40 if (exists($opts{weight}) && length($opts{weight})) {
41 $W = $opts{weight};
42 }
43
44 my $in_cohort = 0;
45 my %readings = ();
46 my %deleted = ();
47 my $trail = '';
48
49 sub sort_weight {
50 my $wa = 0.0;
51 my $wb = 0.0;
52 if ($a =~ m/(?:^|\s)<\Q$W\E:([\d.]+)>(?:\s|$)/ || $a =~ m/(?:^|\s)\Q$W\E:([\d.]+)(?:\s|$)/) {
53 $wa = $1;
54 }
55 if ($b =~ m/(?:^|\s)<\Q$W\E:([\d.]+)>(?:\s|$)/ || $b =~ m/(?:^|\s)\Q$W\E:([\d.]+)(?:\s|$)/) {
56 $wb = $1;
57 }
58
59 if ($wa == $wb) {
60 return $a cmp $b;
61 }
62 return $wa <=> $wb;
63 }
64
65 sub print_sorted_readings {
66 if (!@_) {
67 return;
68 }
69 if (exists($opts{weight})) {
70 @_ = sort sort_weight @_;
71 }
72 else {
73 @_ = sort @_;
74 }
75 if (exists($opts{reverse})) {
76 @_ = reverse @_;
77 }
78 if (exists($opts{first})) {
79 print $_[0];
80 }
81 else {
82 print join('', @_);
83 }
84 }
85
86 sub print_sorted {
87 if (!$in_cohort) {
88 return;
89 }
90
91 print_sorted_readings(keys(%readings));
92 print_sorted_readings(keys(%deleted));
93
94 print $trail;
95
96 %readings = ();
97 %deleted = ();
98 $trail = '';
99 $in_cohort = 0;
100 }
101
102 my $fh = *STDIN;
103 if (defined $ARGV[0]) {
104 open($fh, '<', $ARGV[0]) or die $!;
105 }
106
107 while (<$fh>) {
108 if (m/^"<.+?>"/) {
109 print_sorted();
110 $in_cohort = 1;
111 }
112 elsif ($in_cohort) {
113 if (m/^\s+".+?"/) {
114 $readings{$_} = 1;
115 }
116 elsif (m/^;\s+".+?"/) {
117 $deleted{$_} = 1;
118 }
119 else {
120 $trail .= $_;
121 }
122 next;
123 }
124 print;
125 }
126
127 print_sorted();