fix regression
[hband-tools.git] / tabdata / td-format
blob85ba246a4867cd785d48ac325778b608389a3794
1 #!/usr/bin/env perl
3 =pod
5 =head1 NAME
7 td-format - Print formatted lines per Tabular Data record
9 =head1 SYNOPSIS
11 td-format I<TEMPLATE>
13 =head1 DESCRIPTION
15 =head1 OPTIONS
17 =over 4
19 =item --nofield=[B<empty>|B<leave>|B<name>|B<skip-record>|B<fail>]
21 How to resolve non-existent field names in template variables?
23 =over 8
25 =item B<empty>
27 Replace with empty string.
28 This is the default.
30 =item B<leave>
32 Leave the C<{field_name>}> string there unresolved.
34 =item B<name>
36 Replace with the field name itself.
38 =item B<skip-record>
40 Don't output anything for the given record.
41 Continue with the next one.
43 =item B<fail>
45 Exit the program immediately with error code.
47 =back
49 =item -n
51 No newline.
53 =back
55 =head1 SEE ALSO
57 =cut
60 use Switch;
61 no if ($] >= 5.018), 'warnings' => 'experimental::smartmatch';
64 sub replace_nofield
66 my $fieldname = shift;
67 my $template_fragment = shift;
68 my $callback_data = shift;
70 switch($OptNoFieldBehavior)
72 case('empty') { return ''; }
73 case('leave') { return $template_fragment; }
74 case('name') { return $fieldname; }
75 case('skip-record') { $callback_data->{'skip-record'} = 1; die; }
76 case('fail') { $callback_data->{'fail'} = 1; $callback_data->{'missing-field-name'} = $fieldname; die; }
80 sub render
82 my $s = shift;
83 my $fields = shift;
84 my $callback_data = shift;
85 $s =~ s{\{([^{}]*)\}}{$fields->{$1} // replace_nofield($1, $&, $callback_data)}eg;
86 return $s;
90 @NoFieldBehaviorValues = (qw/empty leave name skip-record fail/);
91 $OptNoFieldBehavior = 'empty';
92 $OptNoNewline = 0;
94 %OptionDefs = (
95 'nofield=s' => \$OptNoFieldBehavior,
96 'n' => \$OptNoNewline,
99 do '/usr/lib/tool/perl5/tabdata/common.pl' or die "$@";
101 pod2usage(-exitval=>2, -verbose=>99) if not $OptNoFieldBehavior ~~ @NoFieldBehaviorValues;
103 @Templates = @ARGV;
107 process_header(scalar <STDIN>);
109 RECORD:
110 while(not eof STDIN)
112 my @row = read_record(\*STDIN);
113 my %fields = map {( $_ => $row[$Header{$_}] )} keys %Header;
114 my $callback_data = {};
115 my $output;
116 eval {
117 $output = join $FS, map {render($_, \%fields, $callback_data)} @Templates; 1;
119 or do {
120 if($callback_data->{'skip-record'}) { next RECORD; }
121 if($callback_data->{'fail'}) { die sprintf "%s: no such field: %s\n", $0, $callback_data->{'missing-field-name'}; }
123 $output .= $RS unless $OptNoNewline;
124 print $output;