# the Albannach method expanded (only read $n_lines from file): #!/usr/bin/perl -w use strict; my $n_lines = 10; my $file = 'blah'; my @lines; open(FILE, $file)|| die "Can't $!"; while(){ push @lines, $_; last if $. == $n_lines; } close FILE; print @lines; __END__ # A slight variation (only reads $n_lines): #!/usr/bin/perl -w use strict; my $n_lines = 10; my $file = 'blah'; my @lines; open(FILE, $file)|| die "Can't $!"; for (1 .. $n_lines) { push @lines, scalar ; } close FILE; print @lines; __END__ # let's read $n_lines one character at a time: #!/usr/bin/perl -w use strict; my $n_lines = 10; my $file = 'blah'; $_ = ''; open(FILE, $file)|| die "Can't $!"; $_ .= getc(FILE) while tr/\n// < $n_lines; close FILE; my @lines = split/^/m; print @lines; __END__ # aww heck, lets read it all but only keep $n_lines: #!/usr/bin/perl -w use strict; my $n_lines = 10; my $file = 'blah'; my @lines; open(FILE, $file)|| die "Can't $!"; @lines[0..$n_lines-1] = ; close FILE; print @lines; __END__ # same idea, different implementation: #!/usr/bin/perl -w use strict; my $n_lines = 10; my $file = 'blah'; open(FILE, $file)|| die "Can't $!"; my @lines = ()[0..$n_lines-1]; close FILE; print @lines; __END__ # stand on someone else's shoulders (or head as the case may be): #!/usr/bin/perl -w use strict; my $n_lines = 10; my $file = 'blah'; my @lines = `head -n$n_lines $file`; print @lines; __END__