Here's a way to do it if your flatfile consists of one record per line, with whitespace before the "record number" at the end:

#!/usr/bin/perl -- -*-fundamental-*- use strict; use Fcntl qw(:flock); ## Set these as needed... my $flatfile = "flat.txt"; my $num2delete = "12"; my $result = &DeleteRecord($flatfile, $num2delete); if ($result) { print "No records were deleted.\n"; } else { print "Deleted record number $num2delete.\n"; } exit; sub DeleteRecord($$) { my $flatfile = shift; my $num2delete = shift; ## Open the flatfile in read/write mode open(FLATFILE, "+< $flatfile") or die "Could not open $flatfile: $!\ +n"; ## Lock it exclusively flock(FLATFILE, LOCK_EX) or die "Could not lock $flatfile: $!\n"; ## Try and find a match my $found=0; while(<FLATFILE>) { last if /\s+$num2delete$/ and ++$found; } ## If no match, we clean up and return a 1 unless ($found) { close(FLATFILE); ## Also unlocks for you return 1; ## Have the caller handle this case; } ## Mark the spot where the record to be deleted starts my $here = tell(FLATFILE) - length $_; ## Read in the rest of the file: my @slurp = <FLATFILE>; ## Rewind to the spot we marked earlier seek(FLATFILE,$here,0); ## Stick everything else back in, overwriting the file as we go: print FLATFILE @slurp; ## If we don't truncate, the last record will appear twice (think ab +out it) truncate(FLATFILE, tell); ## Close and unlock, and return success to the caller close(FLATFILE); return 0; }

In reply to Re: editing/deleting record in flat file database by turnstep
in thread editing/deleting record in flat file database by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.