Deleting a blank line EOF doesn't work

K

Karen

Hi,

I have a perl script that modifies a regular text file, for some
reason it adds an extra blank line at the end of the file.
I've tried to remove it with chomp(), or adding the \r character but
doesn't work.

So far I read the file into an array and try to delete it from there
(the blank line is @file2[107]) I added the following code but doesn't
do anything.

## Rest of the code
$file2="C:\\stocker\\$outputFile";
if(open(FK,"$file2")){
close FK;
tie @file2, "Tie::File", $file2;
splice @file2,107,1; #remove record, starting at record 107
} else{
print "Can't open the file $file2";
}
##
Please help me with some suggestions. I just need to get rid of the
last line in a text file.

Thanks,
-Karen-
 
T

Tad McClellan

Karen said:
if(open(FK,"$file2")){
^ ^
^ ^ a useless use of quotes


What's wrong with always quoting "$vars"?

close FK;


Why go the trouble of open()ing the file only to immediately close it?

If you want to know if a file exists, the use the operator that
tests if a file exists:

if ( -e $file2 ) {

splice @file2,107,1; #remove record, starting at record 107
} else{
print "Can't open the file $file2";


You should always include the $! variable in your diag message:

print "Can't open the file '$file2' $!";
 
V

Vlad Tepes

Karen said:
I have a perl script that modifies a regular text file, for some
reason it adds an extra blank line at the end of the file.
I've tried to remove it with chomp(), or adding the \r character but
doesn't work.
....

Please help me with some suggestions. I just need to get rid of the
last line in a text file.

[ warning: untested ]

If you want to don't mind reading the whole file into memory, you can
use this one-liner to remove last line of 'filename':

perl -i -0777 -pe's/\n.*\Z//' filename

Use this if you want to save the original file to 'filename.temp':

perl -i.temp -0777 -pe's/\n.*\Z//' filename

( This works under linux, other platforms may need doublequotes
and different lineendings. )

Here's a script to do the same thing. It uses little memory, and should
work for big files:

#!/usr/bin/perl

use strict;
use warnings;

my $original = 'C:\stocker\file.txt';
my $tempfile = $original . '.temp';

open my $orig, $original or die "Can't read $original: $!";
open my $temp, ">$tempfile" or die "Can't write $tempfile: $!";

my $lastline = '';
while ( <$orig> ) {
print $temp $lastline;
$lastline = $_;
}

rename $tempfile, $original
or die "Can't rename $tempfile to $original: $!";

__END__
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top