Timothy Duke wrote:
> 
> Hi,

Hello,

> I have got two versions of a script to eliminate single line-feeds from
> a file.

You should use chomp() to remove newlines.  Using the substitution
operator globally is forcing the whole line to be scanned.

> The first one does weird stuff - duplicating lines and messing
> the text file up.

That is because you are using '+<', the read/write mode.

> The second one works (I copied it from a Perl guide),
> but I don't understand why.

That is because Perl's <> operator and the $^I variable do all the work
behind the scenes of managing your file and the backup file.

> I would much prefer the first one to work -
> Can you tell me how to change the first one to make it work?

Yes.

> Also, I understand that the <> operator reads in one line at a time.

It opens one "line" at a time where a "line" is defined by the value of
the input record separator ($/) which is set to "\n" by default.

> If
> I wish to eliminate only triple line-feeds (\n\n\n) and leave double and
> single linefeeds, I presume <> won't work.  Without reading in the whole
> file at once, how can I achieve this?

Set the input record separator to paragraph mode.


> ----------------------------------------------------
> 
> Version #1 (works dreadfully....stuffs up the file)
> 
> #! perl  -w -i
> $filetobechanged = "iBook HD:Desktop Folder:tim.txt";
> open(FILE, "+< $filetobechanged") ;

You should *ALWAYS* verify that the file opened correctly.


> while (<FILE>) {
>      s/\n//g;
>      print FILE ;

In read/write mode you read line one and then print over line two and
then read line three and then print over line four, etc.


>          }
> close(FILE);
> 
> Version #2 (works fine)
> $filetobechanged = "iBook HD:Desktop Folder:tim.txt";
> @ARGV = ($filetobechanged);
> $^I = ".bak";
> while (<>) {
>      s/\n//g;;
>      print;
> }

If I understand correctly, you can achieve what you want like this:

#! perl -w
use strict;
( $/, $^I, @ARGV ) = ( '', '.bak', 'iBook HD:Desktop Folder:tim.txt' );
print while <>;


However, since you seem to want to open the files yourself, you could do
it like this:

#! perl -w
use strict;

my $filetobechanged = 'iBook HD:Desktop Folder:tim.txt';
my $backup_file = "$filetobechanged.bak";

rename $filetobechanged, $backup_file
    or die "Cannot rename $filetobechanged, $backup_file: $!";

open BACK, '<', $backup_file     or die "Cannot open $backup_file: $!";
open FILE, '>', $filetobechanged or die "Cannot open $filetobechanged:
$!";

$/ = '';  # Set paragraph mode

while ( <BACK> ) {
    print FILE;
    }

close BACK;
close FILE;

__END__



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to