in reply to Re: Reading and writing to files
in thread Reading and writing to files

That's correct: you cannot add something to the beginning of a file without rewriting the whole file.

As it seems, the code does not implement one of the required tasks: 'then remove those 3 lines from daily.txt'.

Of course, this can be fixed:

#!/usr/bin/perl -w my $daily="daily.txt"; my $weekly="weekly.txt"; my $lines=3; # alternatively, read the names from the command line: # my($daily,$weekly,$lines)=@ARGV; # read the daily file: open DAILY, $daily or die "open $daily: $!"; my @daily=<DAILY>; close DAILY; # read the weekly file: open WEEKLY, $weekly or die "open $weekly: $!"; my @weekly=<WEEKLY>; close WEEKLY; # if the last line of @daily has no \n, this line will # be merged with the first line of @weekly. We are # paranoid and make sure it is there! $daily[-1]=~/\n$/ or $daily[-1].="\n"; # Well. That's good for Unix, not for Windows. You would # have to change "\n" to whatever is appropriate. # move the last $lines lines from the end of @daily to # the beginning of @weekly. Note: # splice(@daily, -$lines) removes and returns the last # $lines lines from @daily; # unshift @weekly, @some_lines adds some lines at the # beginning of @weekly. Together: unshift @weekly, splice(@daily, -$lines); # Write back the weekly file: open WEEKLY, ">$weekly" or die "open >$weekly: $!"; print WEEKLY @weekly; close WEEKLY; # Write back the daily file: open DAILY, ">$daily" or die "open >$daily: $!"; print DAILY @daily; close DAILY;

You might be interested in the splice and unshift manpages for documentation of the main step of this program.

By the way: It is possible to append to the end of a file by opening it with open FILE, ">>$name".

With the truncate function, you can truncate a file (chop off the end leaving the beginning in place). However, I wouldn't recommend that: this function may not be implemented on some systems. Also, it's much simpler to overwrite the file.