Question

I have files with daily stocks prices saved in text files when each line of the file represents one day data. For example:

20/05/2013  23.46   23.58   23.43   23.57   32884800    23.57
17/05/2013  23.27   23.48   23.2    23.46   41037700    23.46

I have created an updater which checks the last date in the saved file (the last date appears at at the top of the file), compares it to the current date and if not equal updates the missing data by appending the missing lines only (the new lines are added on top of the existing file).

I have used this approach to append the lines:

open my $in,  '<',  $file      or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";

print $out "# Add this line to the top\n";

while( <$in> )
    {
    print $out $_;
    }

close $out;

And generally it works fine with only one problem. There is one empty line being added between the oldest line and first new added line. For example, if my last saved date was

15/05/2013  23.04   23.25   22.91   23.24   40153000    23.24

and then new line is being added:

16/05/2013  23.1    23.35   23.1    23.27   33023300    23.27

It will look like that:

15/05/2013  23.04   23.25   22.91   23.24   40153000    23.24

16/05/2013  23.1    23.35   23.1    23.27   33023300    23.27

I want it to look like that:

15/05/2013  23.04   23.25   22.91   23.24   40153000    23.24
16/05/2013  23.1    23.35   23.1    23.27   33023300    23.27

I thought to get rid of the \n when adding the lines but then it will produce just one long string. I guess I should somehow remove the \n but just for the last line. How do I do that?

EDIT: Line endings seem to be just LF, not CRLF. Does that matter? Because currently it seems that the line is not matching the empty line pattern like this or this: /^\s*$/ or this: /^$/.

No correct solution

OTHER TIPS

You can use chomp to intelligently eat newlines (in case of untranslated CRLF), then actually output a newline. In between, you can skip if the line is empty:

while( <$in> )
{
    chomp; chomp;        # Eat up to two newlines, just in case
    next if /^\s*$/;     # Line is empty or contains whitespace
    print $out "$_\n";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top