Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 32 additions & 14 deletions bin/cat
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,24 @@ use constant EX_FAILURE => 1;
our $VERSION = '1.3';
my $Program = basename($0);

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

my $ends = exists $options{'e'};
my $tabs = exists $options{'t'};
my $nonprinting = exists $options{'v'} || $ends || $tabs;
my $squeeze_empty = exists $options{'s'};
my $number_lines = $options{'n'} && !$options{'b'};
my $number_non_blanks = exists $options{'b'};
my $ends = $opt{'e'};
my $tabs = $opt{'t'};
my $nonprinting = $opt{'v'} || $ends || $tabs;
my $squeeze_empty = $opt{'s'};
my $number_lines = $opt{'n'} && !$opt{'b'};
my $number_non_blanks = $opt{'b'};

my $cook = grep {$_ || ()} @opt{'b', 'e', 'n', 's', 't', 'v'};
my $cat = $cook ? \&cook_file : \&raw_file;

# Unbuffer output for -u.
$| = exists $options{'u'};
$| = 1 if $opt{'u'};

my $was_empty = 0;
my $count = 0;
Expand Down Expand Up @@ -70,9 +74,28 @@ sub do_file {
return 1;
}
}
$cat->($fh);

while (<$fh>) {
if ($name ne '-' && !close($fh)) {
warn "$Program: failed to close '$name': $!\n";
return 1;
}
return 0;
}

sub raw_file {
my $fh = shift;
my $BUFSZ = 8192;
my $buf;
while (read $fh, $buf, $BUFSZ) {
print $buf;
}
}

sub cook_file {
my $fh = shift;

while (<$fh>) {
if ($squeeze_empty) {
my $is_empty = /^$/;
if ($is_empty && $was_empty) {
Expand All @@ -96,11 +119,6 @@ sub do_file {
}
print;
}
if ($name ne '-' && !close($fh)) {
warn "$Program: failed to close '$name': $!\n";
return 1;
}
return 0;
}

__END__
Expand Down