text file modification...

r_kar used Ask the Experts™
Hi all,

I want to edit a text file. The text file (contain two values, separated by :) format is as follows:


I am reading this file and listed all values using a checkbox (Done code for this part) and a delete button.
If i select checkbox(es) and go for delete(operation) the selected values, i would like to modify the text file. Please provide a code to handle this.

Thanks in advance
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
When modifying a file from a CGI program, you must take steps to prevent more than one process from attempting to modify the the file at the same time.

Let me assume you're using the CGI module or something like to so that we have

$op = query->param('operation'); # $op eq 'delete'
@names = query->param('names');
$datafile = 'datafile.txt' ; # change this name as needed

# set up a hash with the selected names as keys
map { $selected{$_}++; } @names;

open NAMES, "+<$datafile";

flock NAMES, 2; # exclude others

@lines = <NAMES>; # slurp entire file

seek NAMES, 0, 0; # rewind
truncate NAMES, 0; # prepare for rewriting

foreach ( @lines ) {
    ($left, $right) = split ';';
    chomp $right;
    unless ( $op eq 'delete' && $selected{$right} ) {
        print NAMES;

close NAMES; # flushes and unlocks it, too


Now, aside from transcription and typo bugs I may have introduced, this is the same code as I tested out some months ago as an AskMe.com answer. You may find it suitable for what you're doing but as CGI code, I usually found I wanted to display something back that described what was going on, which was best generated in the loop around foreach( @lines).

Your example data file has the names of numbers in the left hand field. These will no longer be consecutive if you do deletions this way.



Thanks for your reply.
I will go through your comment and award the ee points.


Excellent work.
Sorry for the delay.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial