wickedxter has asked for the wisdom of the Perl Monks concerning the following question:

This is the code i use to edit data in the file, this code finds the data and then removes the data from the file with the new line, but i dont want it to make new lines i want it to remove the data and then move the rest of the data up where the removed data was.
open(FILE,"$location/$file"); flock(FILE,2); @data = <FILE>; close(FILE); open(FILE,"$location/$file"); while (<FILE>){ ($name,$dir,$des,$dl,$style) = split(/\|/); if($name eq "$cat_name_del"){ print FILE "\n"; } else { print FILE "$name|$dir|$dl|$style|\n"; } }

Replies are listed 'Best First'.
Re: remove new lines in flat files
by jlongino (Parson) on Sep 03, 2001 at 22:15 UTC
    I'm not sure if I understand exactly what you want to do, but you probably want to leave off the

    "\n"

    from your print statements. Either that or do a

    chomp @data;

    after the

    @data = <FILE>;

    which is less efficient in this case.

    Update: Also you probably want to rewrite your if statement to look so, since the if part is not needed:

    if($name ne "$cat_name_del"){ print FILE "$name|$dir|$dl|$style|\n"; }
    @a=split??,'just lose the ego and get involved!';
    for(split??,'afqtw{|~'){print $a[ord($_)-97]}
Re: remove new lines in flat files
by tachyon (Chancellor) on Sep 03, 2001 at 22:55 UTC
    my $file = "c:/test.txt"; # open file for both reading and writing open FILE, "+<$file" or die "Can't open $file: $!\n"; my @file = <FILE>; # get all data make_backup($file, @file); # make a backup seek FILE, 0, 0; # go to beginging of file truncate FILE, 0; # delete all the old data # now write only the lines we want back to file # the newlines are still attached to each line for my $line (@file) { print FILE $line unless $line eq "don't print\n"; } close FILE; # sub to write a backup sub make_backup { my $file = shift; open BACKUP, ">$file.bak" or die "Can't write $file.bak: $!\n"; print BACKUP @_; close BACKUP; }

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

      thx tachyon it worked..
Re: remove new lines in flat files
by Hofmator (Curate) on Sep 04, 2001 at 12:36 UTC

    I just throw in the one liner: perl -i.bak -F\\\| -ane 'print unless $F[0] eq q/cat_name_del/' datafile

    -- Hofmator