#!/usr/bin/perl # okay, so I messed up, whatever, I'll just rewrite the head utility :-P # default lines to read my $lines = 10; # there might be two command line arguments -n $i, # which we need to remove from @ARGV if ( @ARGV ) { # process args, will implement both -n 10 and -10 if ( $ARGV[0] =~ qr/^-(.+)$/ ) { my $flag = $1; # using traditional api if ( $flag eq 'n' ) { $lines = $ARGV[1]; # if it's not an integer above zero, print msg and quit if ( $lines !~ qr/^\d+$/ or $lines <= 0 ) { print "head: Invalid \"-n $lines\" option\n"; print "usage: head [-n #] [-#] [filename...]\n"; exit 1; } # remove args from @ARGV shift(@ARGV); shift(@ARGV); } # maybe first arg is -10, not actually used by darwin, though! elsif ( $flag =~ qr/^\d+$/ ) { $lines = $flag; # if it's not an integer above zero, print msg and quit if ( $lines <= 0 ) { print "head: Invalid \"-n $lines\" option\n"; print "usage: head [-n #] [-#] [filename...]\n"; exit 1; } # remove arg from @ARGV shift(@ARGV); } # some other flag was used! else { print "head: illegal option -- $flag\n"; print "usage: head [-n #] [-#] [filename...]\n"; exit 1; } } } # additional arguments are file names if ( @ARGV ) { # more than one file? print header my $more_than_one_file = $#ARGV; # need to add a line break before ==> XXX <== after first file my $files_read = 0; # loop over remaining args for my $arg ( @ARGV ) { open ( my $handle, '<', $arg ) or print "$arg: $!\n" and exit 1; print "\n" if $files_read++; print "==> $arg <==\n" if $more_than_one_file; my $counter = 0; PRINT_FROM_FILE: while ( defined( my $line = <$handle> ) ) { print $line; last PRINT_FROM_FILE if ++$counter == $lines; } close $handle; } # no further behaviour exit 0; } my $counter = 0; PRINT_FROM_STRING: while(<>){ print; last PRINT_FROM_STRING if ++$counter == $lines; }