Skip to content

Commit

Permalink
Merge pull request #227 from mknos/head-dir
Browse files Browse the repository at this point in the history
head versus directories
  • Loading branch information
briandfoy authored Sep 6, 2023
2 parents dc29f7a + 61d43f3 commit 172621d
Showing 1 changed file with 46 additions and 12 deletions.
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

0 comments on commit 172621d

Please sign in to comment.