Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with grabing last ten lines. 1

Status
Not open for further replies.

ETbyrne

Programmer
Dec 27, 2006
59
US
I'm having trouble printing the last ten lines from a text file to another text file. It works until it gets to the line 20 and I get this error...

Use of uninitialized value in string at e:\0\74\38\237038\user\240783\htdocs\mywebs\ETbyrne\cgi-bin\redalert\ten_newest_maps.pl line 20.

here's my script:
Code:
#!/usr/bin/perl
use warnings;
use strict;
use CGI qw(:standard);
use Fcntl qw(:flock :seek);

open(FILE, ">>./mywebs/ETbyrne/redalert/links.txt") or die "Can not open links.txt: $!";
seek(FILE,0,0);
my @file = <FILE>;
@file = reverse(@file);
close FILE;

open(FH, "+<./mywebs/ETbyrne/redalert/newmaps.txt") or die "Cannot open newportals.txt: $!";
flock(FH,LOCK_EX);
seek(FH,0,SEEK_SET);

truncate(FH,0);

seek(FH,0,SEEK_SET);
print FH "$file[$_]" for (0..9); # This is line 20 #
close (FH);

print "<html><head><title>Thank You</title></head>\n";
print "<body>\n";
print "Your Map was added. click <a href=\"index.shtml\">here</a> to go to the home page.<br>\n";
print "</body></html>\n";
Thanks for all help.

_______________________________________

You don't know me.
 
I think perhaps you're overcooking with the file open/seeks/etc... and you seem to have the directions back-to-front.

Code:
#!/usr/bin/perl
use warnings;
use strict;
use CGI qw(:standard);
use Fcntl qw(:flock :seek);

open(FILE, "<links.txt") or die "Can not open links.txt: $!";
my @file = <FILE>;
@file = (reverse(@file))[0..9];
close FILE;

open(FH, ">newmaps.txt") or die "Cannot open newmaps.txt: $!";
print FH foreach @file;
close (FH);

print "<html><head><title>Thank You</title></head>\n";
print "<body>\n";
print "Your Map was added. click <a href=\"index.shtml\">here</a> to go to the home page.<br>\n";
print "</body></html>\n";

As I understand it, a process prior to this one appends each new map to links.txt, and you want the last 10 in reverse order (newest first).

Obviously, add the full paths in your open statements....
 
Thanks, it works now, but I kept one of the locks in so that the file newmaps.txt doesn't get corrupted when two people run the script at once.

_______________________________________

You don't know me.
 
You might want to look into using Tie::File, you can read and write files almost exactly like you do with a perl array.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top