in reply to Replace first blank line in a text file with headers.

Here's a way to do it with Tie::File:
use strict; use warnings; use Tie::File; my $filename = 'dir/people.txt'; tie my @array, 'Tie::File', $filename or die "Could not open file '$fi +lename' $!"; $array[0] = 'Name, City, State, Zip' unless $array[0] =~ /\S/; untie @array;

Replies are listed 'Best First'.
Re^2: Replace first blank line in a text file with headers.
by Anonymous Monk on Mar 24, 2016 at 15:33 UTC
    Never used "Tie::File" before:
    "Using Tie::File module. This module makes a file look like a Perl arr +ay,each array element corresponds to a line of the file. Tie::File is very efficient; instead of rewriting the entire file, it +just rewrites what is necessary to apply the modification you specify +."
    Thanks for the idea!!!
Re^2: Replace first blank line in a text file with headers.
by Anonymous Monk on Mar 24, 2016 at 18:34 UTC
    It works the first time, but the second time I run the code the blank line returns because its not on the first line any more,but its the first line on the new chunk of data been append to the file.
    Could I run this:
    tie my @array, 'Tie::File', $filename or die "Could not open file '$fi +lename' $!"; $array[0] = 'Name, City, State, Zip' unless $array[0] =~ /A\s*\Z/; $_ = '' unless $_ =~ /A\s*\Z/; untie @array;
    To get rid of any other empty line in the file once I check for the empty line been at the beginning of it? </code>
Re^2: Replace first blank line in a text file with headers.
by Anonymous Monk on Mar 24, 2016 at 23:13 UTC
    Hi, I am using Tie::File, since it seems to be a straight forward way, could someone take a look if there is a better way of doing this?
    tie my @array, 'Tie::File', $filename or die "Could not open file '$fi +lename' $!"; # First if the first line does not start with "Name" it means there is +n't any headers, # add headers to the file: unshift @array, 'Name, City, State, Zip' unless $array[0] =~ /Name/; # Check the whole file if there is any blank lines, if there is, get r +id of it @array = grep /\S/, @array; untie @array;
    Thank you!