Skip to content

Commit edf912c

Browse files
authored
cat: add raw mode (#638)
* Implement idea from BSD version of cat: bypass input processing if none of options -b -e -n -s -t & -v are provided
1 parent 017339a commit edf912c

File tree

1 file changed

+32
-14
lines changed

1 file changed

+32
-14
lines changed

bin/cat

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,24 @@ use constant EX_FAILURE => 1;
2222
our $VERSION = '1.3';
2323
my $Program = basename($0);
2424

25-
getopts('benstuv', \my %options) or do {
25+
my %opt;
26+
getopts('benstuv', \%opt) or do {
2627
warn "usage: $Program [-benstuv] [file ...]\n";
2728
exit EX_FAILURE;
2829
};
2930

30-
my $ends = exists $options{'e'};
31-
my $tabs = exists $options{'t'};
32-
my $nonprinting = exists $options{'v'} || $ends || $tabs;
33-
my $squeeze_empty = exists $options{'s'};
34-
my $number_lines = $options{'n'} && !$options{'b'};
35-
my $number_non_blanks = exists $options{'b'};
31+
my $ends = $opt{'e'};
32+
my $tabs = $opt{'t'};
33+
my $nonprinting = $opt{'v'} || $ends || $tabs;
34+
my $squeeze_empty = $opt{'s'};
35+
my $number_lines = $opt{'n'} && !$opt{'b'};
36+
my $number_non_blanks = $opt{'b'};
37+
38+
my $cook = grep {$_ || ()} @opt{'b', 'e', 'n', 's', 't', 'v'};
39+
my $cat = $cook ? \&cook_file : \&raw_file;
3640

3741
# Unbuffer output for -u.
38-
$| = exists $options{'u'};
42+
$| = 1 if $opt{'u'};
3943

4044
my $was_empty = 0;
4145
my $count = 0;
@@ -70,9 +74,28 @@ sub do_file {
7074
return 1;
7175
}
7276
}
77+
$cat->($fh);
7378

74-
while (<$fh>) {
79+
if ($name ne '-' && !close($fh)) {
80+
warn "$Program: failed to close '$name': $!\n";
81+
return 1;
82+
}
83+
return 0;
84+
}
85+
86+
sub raw_file {
87+
my $fh = shift;
88+
my $BUFSZ = 8192;
89+
my $buf;
90+
while (read $fh, $buf, $BUFSZ) {
91+
print $buf;
92+
}
93+
}
94+
95+
sub cook_file {
96+
my $fh = shift;
7597

98+
while (<$fh>) {
7699
if ($squeeze_empty) {
77100
my $is_empty = /^$/;
78101
if ($is_empty && $was_empty) {
@@ -96,11 +119,6 @@ sub do_file {
96119
}
97120
print;
98121
}
99-
if ($name ne '-' && !close($fh)) {
100-
warn "$Program: failed to close '$name': $!\n";
101-
return 1;
102-
}
103-
return 0;
104122
}
105123

106124
__END__

0 commit comments

Comments
 (0)