Hi,
I am in a dilemma for which it appears my understanding of the seek and tell functions is lacking.
I am writing code whose purpose is to take a file and if the number of lines of the file is a certain limit, remove the final line. Also, add a line to the beginning of the file.
The procedure I am using is to write the file to an array, check its size and pop if line limit is reached. Then, open the same file, go to position 0, write out the new line, and then write out the contents of the array. Finally, truncate the rest of the file. (I realize I could just delete the file, but want to be able to use - understand - the seek, tell, and truncate functions.)
My dilemma is that after I run my code, the line that I want to be first IS LAST. This caused me to consider that perhaps the seek function KEEPS the file position at 0 (instead of "walking" along what is being written), but wouldn't this then mean the array would appear in reverse order (to be consistent)? (It doesn't.)
Anyway, here is the code and my summary questions are:
Why is the line I intend to be first, last?
Why is the array outputted in sequential order?
Any recommended diagnostics I could have done to solve the problem myself?
Thanks in advance for any assistance.
Tony (o2bwise)
My Code:
#!/usr/bin/perl -w
use strict;
my @messagesIn;
my $MAXSAVE = 12;
my $name = "Duane Wade";
my $subject = "My Career";
my $message = "No one ever thought I'd be this good.";
flock("messageTest.txt",2);
open(FROMFILE,"<messageTest.txt");
while (<FROMFILE>)
{
chomp $_;
push (@messagesIn, $_);
}
while (@messagesIn > $MAXSAVE)
{
pop (@messagesIn);
}
close(FROMFILE);
flock("messageTest.txt",8);
open (TOFILE,">>messageTest.txt");
flock("messageTest.txt",2);
seek(TOFILE,0,0);
print TOFILE "$name|$subject|$message\n";
my $counter = 0;
while ( $counter < @messagesIn )
{
print TOFILE "$messagesIn[$counter]\n";
$counter++;
}
truncate(TOFILE, tell(TOFILE));
flock("messageTest.txt",8);
close (TOFILE);
1;