#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 1999
    Location
    London
    Posts
    110
    Rep Power
    0
    hi

    i need to open a file, read a line and then compare that to the line below it, if it matches delete the first and then compare the line after it, basically running through checking each line against the next.
    i can open the file, read through it, out put and do the checking, I was doing it it as a for loop (of 2) and then slowly chugging through, but I'm sure there must be a more efficient way of doing this.

    any thoughts anyone, help greatly appreciated

    tia

    t
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2000
    Posts
    81
    Rep Power
    14
    Simplest way to do it is this:
    <BLOCKQUOTE><font size="1" face="Verdana,Arial,Helvetica">code:</font><HR><pre>
    use File::Copy;

    open INFILE, $myfile or die "Failed to open $myfile for input: $!";
    open OUTFILE, ">$myfile.out" or die "Failed to open $myfile.out for output: $!";
    my $current = <INFILE>;
    while( my $next = <INFILE> ) {
    print OUTFILE $current if $current ne $next;
    $current = $next;
    }
    print OUTFILE $current;
    close OUTFILE;
    close INFILE;
    copy( "$myfile.out", $myfile );
    [/code]
    It's alright efficiency-wise, but has two major problems:
    1) It requires enough disk space to write out another copy of the file (without the line duplications)
    2) It requires a copy of the file

    It also leaves the temporary file there, but deleting that is easy enough.
    Neither of these two problems should cause too much of an issue if you're not working with overly larger files, but it could be a problem if you are. You MIGHT be able to overcome these using lower level read/write routines on a single file, but even if you can (which I'm not sure is all that likely), you'll probably have to go through quite a lot of pain to get it to work. At least the way detailed above doesn't require a lot of memory (just enough to hold two lines at a time) so you shouldn't hit problems that way.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 1999
    Location
    London
    Posts
    110
    Rep Power
    0
    cheers chris

    worked far better than mine did

    though you got round the need for duplication by copying the new over the orig, so I changed that to rename so you end up with one file.


    thanks again

    tim

IMN logo majestic logo threadwatch logo seochat tools logo