[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Would like suggestion.



>>> My question involves is this: When 3 (or "N") or more blank lines are
>>> found, delete them. Leaving 2 in their place, and possibly a marker.
>> 
>> Here is a very simple way of doing it, however it might be a memory hog:
>> 
>> open (TEXT, "MyFile.file");     ### This opesn up the file.
>> my @Lines = <TEXT>;             ### This sticks it into an array.
>> close TEXT;                     ### This closes the file.
> 
> Certainly, having two copies of the file will be more of a memory hog than
> having one:

It just _might_ be a memory hog!?  I remember my old 8mbsystem that could
barely fathom undef $/.  To save some memory (but sacrifice some time), try
this on for size:

$max_returns = 3;             # this is your N number of returns
$replacement_string = "\n\n"; # what you want to replace those N returns
with

$old = "file1"; # has extra lines
$new = "file2";

open(OLD, "< $old");
open(NEW, "> $new");

OUTER:
while(<OLD>) {
    if(length == 1) {
        my $pos = tell(OLD);
        $returns++;

        INNER:
        while(my $line = <OLD>) {
            if(length($line) == 1) { $returns++ }
            else { last }
            $pos = tell(OLD); # get pos, so OUTER doesn't get lost
        }
        
        seek(OLD, $pos, 0);
        
        my $print_str = ($returns >= $max_returns ? $replacement_string :
("\n" x $returns));
        print NEW $print_str;
    } else {
        $returns = 0; # reset return counter
        print NEW;
    }
}

close(OLD);
close(NEW);

It could be tidied up a bit, I know... I just wanted to get the code to you
as soon as I thought of it!  Oh and one more caveat: It's not the fastest
solution, but it'll help ease your memory concerns :)

Regards,
David


# ===== Want to unsubscribe from this list?
# ===== Send mail with body "unsubscribe" to macperl-request@macperl.org