Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

head versus directories #227

Merged
merged 2 commits into from
Sep 6, 2023
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
58 changes: 46 additions & 12 deletions bin/head
Original file line number Diff line number Diff line change
Expand Up @@ -13,32 +13,66 @@ License: perl


use strict;
use Getopt::Std;

my ($VERSION) = '1.3';
use File::Basename qw(basename);
use Getopt::Std qw(getopts);

my %opt;
getopts('n:', \%opt) or die("usage: $0 [-n count] [files ...]\n");
use constant EX_SUCCESS => 0;
use constant EX_FAILURE => 1;

my $count = (defined $opt{'n'}) ? $opt{'n'} : 10;
my $Program = basename($0);
my ($VERSION) = '1.3';

die "invalid number `$count'\n" if $count =~ /\D/;
my %opt;
unless (getopts('n:', \%opt)) {
warn "usage: $Program [-n count] [file ...]\n";
exit EX_FAILURE;
}
my $count;
if (defined $opt{'n'}) {
$count = $opt{'n'};
if ($count =~ m/\D/a) {
warn "$Program: invalid number '$count'\n";
exit EX_FAILURE;
}
if ($count == 0) {
warn "$Program: count is too small\n";
exit EX_FAILURE;
}
} else {
$count = 10;
}

@ARGV = '-' unless @ARGV;
my $err = 0;
my $sep = 0;

foreach my $file (@ARGV) {
my ($fh, $is_stdin);
if ($file eq '-') {
$fh = *STDIN;
$is_stdin = 1;
} else {
if (-d $file) {
warn "$Program: '$file' is a directory\n";
$err++;
next;
}
unless (open $fh, '<', $file) {
warn "$Program: $file: $!\n";
$err++;
next;
}
}
if (!$is_stdin && !open($fh, '<', $file)) {
warn "$0: $file: $!\n";
next;
}

if (scalar(@ARGV) > 1) {
my $fname = $is_stdin ? 'standard input' : $file;
print "==> $fname <== \n";
if ($sep == 0) {
$sep = 1;
} else {
print "\n";
}
print "==> $fname <==\n";
}
foreach (1 .. $count) {
my $line = <$fh>;
Expand All @@ -47,7 +81,7 @@ foreach my $file (@ARGV) {
}
close($fh) unless $is_stdin;
}

exit ($err ? EX_FAILURE : EX_SUCCESS);

__END__

Expand Down