Tweet

How do I print the first line of a file?

You have a file from which you wish to print the first line, do some processing, then print the rest of the file.

A sample file

    We want to print this line first
    Then print these lines after doing some other work
    And this line
    And this line too

The problem code

    #!/usr/bin/perl -w
    use strict;
    use warnings;
    my $file = "...";

    open (CODE, $file) || die "Couldn't open $file: $!";
    while (<CODE>) {
        print $_;
    }
    close CODE;

...which gives the entire file. But you want to see...

    We want to print this line first
    This bit not from the file
    Then print these lines after doing some other work
    And this line
    And this line too

Solution:

Read in the first line, do your processing, then continue reading the file.

    #!/usr/bin/perl -w
    use strict;
    use warnings;
    my $file = "...";

    open (CODE, $file) || die "Couldn't open $file: $!";

    print scalar <CODE>;	# Print the first line

    # ... Do your processing here ...
    print "This bit not from the file\n";

    while (<CODE>) {
        print $_;
    }
    close CODE;

...which gives you the correct output.

Revision: 1.5 [Top]