#!/usr/bin/perl

=begin metadata

Name: head
Description: print the first lines of a file
Author: Abigail, perlpowertools@abigail.be
License: perl

=end metadata

=cut


use strict;
use Getopt::Std;

my ($VERSION) = '1.3';

my %opt;
getopts('n:', \%opt) or die("usage: $0 [-n count] [files ...]\n");

my $count = (defined $opt{'n'}) ? $opt{'n'} : 10;

die "invalid number `$count'\n" if $count =~ /\D/;

@ARGV = '-' unless @ARGV;

foreach my $file (@ARGV) {
    my ($fh, $is_stdin);
    if ($file eq '-') {
        $fh = *STDIN;
        $is_stdin = 1;
    }
    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";
    }
    foreach (1 .. $count) {
        my $line = <$fh>;
        last unless (defined $line);
        print $line;
    }
    close($fh) unless $is_stdin;
}


__END__

=pod

=head1 NAME

head - print the first lines of a file

=head1 SYNOPSIS

head [-n count] [files ...]

=head1 DESCRIPTION

I<head> prints the first I<count> lines from each file. If the I<-n> is
not given, the first 10 lines will be printed. If no files are given,
the first lines of standard input will be printed.

=head2 OPTIONS

I<head> accepts the following options:

=over 4

=item -n count

Print I<count> lines instead of the default 10.

=back

=head1 ENVIRONMENT

The working of I<head> is not influenced by any environment variables.

=head1 BUGS

I<head> has no known bugs.

=head1 STANDARDS

This I<head> implementation is compliant with the B<IEEE Std1003.2-1992>
specification, also known as B<POSIX.2>.

This I<head> implementation is compatible with the B<OpenBSD> implementation.

=head1 AUTHOR

The Perl implementation of I<head> was written by Abigail, I<perlpowertools@abigail.be>.

=head1 COPYRIGHT and LICENSE

This program is copyright by Abigail 1999.

This program is free and open software. You may use, copy, modify, distribute
and sell this program (and any modified variants) in any way you wish,
provided you do not restrict others to do the same.

=cut