Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is there any command or any other option in perl to read the first n number of lines from a file? I would be thankful if anyone can help.

Replies are listed 'Best First'.
Re: Unix 'head' in perl
by edan (Curate) on May 14, 2003 at 13:58 UTC
    perl -pe 'BEGIN{ $lines = 10 } last if $. > $lines' < file

    Update: my perlgolf entry is:

    perl -pe'$.>10&&last' file
    --
    3dan
Re: Unix 'head' in perl
by Ovid (Cardinal) on May 14, 2003 at 13:58 UTC

    Many ways you can do this. Here's one:

    use strict; use warnings; my $file = shift; print head($file); sub head { my ($file,$count) = @_; $count ||= 10; open FILE, '<', $file or die "Cannot open ($file) for reading: $!"; my @data; while (defined (my $line = <FILE>)) { push @data => $line; last if $. >= $count; } close FILE or die "Cannot close ($file): $!"; return @data; }

    Cheers,
    Ovid

    New address of my CGI Course.
    Silence is Evil (feel free to copy and distribute widely - note copyright text)

Re: Unix 'head' in perl
by BrowserUk (Patriarch) on May 14, 2003 at 14:03 UTC

    Adjust as required.

    perl -ple" exit if $. == 20" file

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
      which only prints 19 lines of the file...
      --
      3dan

        Good point!

        perl -ple"exit if $. > 20"

        Examine what is said, not who speaks.
        "Efficiency is intelligent laziness." -David Dunham
        "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
Re: Unix 'head' in perl
by Limbic~Region (Chancellor) on May 14, 2003 at 16:53 UTC