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

Dear Monks,

How do I print out a line to a file with the condition it only prints if this line is to constitute the first line of the file. Is there a one liner that will allow me to do that?
  • Comment on Printing a line only if first line of file

Replies are listed 'Best First'.
Re: Printing a line only if first line of file
by davido (Cardinal) on Feb 01, 2008 at 11:41 UTC

    perl -ne "$. ==1 and print;" filename.txt
    perl -e "print scalar <>;" filename.txt
    perl -ne "print and last;" filename.txt
    perl -ne "last; END{print}" filename.txt
    perl -ne "die $_;" filename.txt
    perl -pe "$. > 1 and last;" filename.txt

    Some will be more efficient than others.

    The point is that if all you need to print is the first line, you should probably terminate reading the file once you've read the first line.


    Dave

      perl -ne 'print && close ARGV' filename.txt
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Printing a line only if first line of file
by jettero (Monsignor) on Feb 01, 2008 at 11:22 UTC
    perl -ne 'print $_ unless $. >1'

    ... it even works on stdin.

    -Paul

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Printing a line only if first line of file
by eric256 (Parson) on Feb 01, 2008 at 15:56 UTC

    I think you confused some people You want to know, how do you print a line to the file if the file doesn't exist already? I think the following does what you are asking, you could remove the new lines and make it one line if you wanted but I wouldn't recommend it.

    unless -e $file { open( my $fh, '>', $file) or die "Failed to open '$file': $!"; print $fh "Header"; }

    Update: If you use IO::All then you could do  'Header' > io('test.txt') unless -e 'test.txt';


    ___________
    Eric Hodges
Re: Printing a line only if first line of file
by KurtSchwind (Chaplain) on Feb 01, 2008 at 15:42 UTC

    Some great solutions. How about:

    head -1

    Assuming a *nix platform.

    --
    I used to drive a Heisenbergmobile, but every time I looked at the speedometer, I got lost.