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

I have a program that basically goes out, grabs info from a few different files, then creates a flat file. What I need to do, is test for a duplicate "field string", and append a character to it, before the program actually prints the file.. eg: string = aaa.bb.c 0/0 17 .01888877773 duplicate string = aaa.bb.c 12/12 17 .01888877773 what I need to do is append the character to the 1st. field. How?
  • Comment on Search for dupe && append char if found

Replies are listed 'Best First'.
Re: Search for dupe && append char if found
by BlaisePascal (Monk) on Aug 22, 2000 at 12:09 UTC
    I'm not sure what you mean by "how will the program know which string to modify?". I assume the answer to that would be "by following the algorithm, and modifying the string the algorithm says to".

    One of the standard tricks for detecting duplicates is by using a hash:

    # Read passwd files from @ARGV, outputting one record per # username my %users; while (<>) { $user = split ":",$_,1; next if exists $users{$user}; print; $users{$user} = 1; }
    The first time username foo is found, $users{'foo'} does not exist, so the record is printed out, and $users{'foo'} is set to 1. The second time username foo is found, $users{'foo'} is now 1, so the record is skipped.

    You didn't want to skip records, but rather rekey the records, so that the duplicates have different keys -- you wanted your outputted flat-file to have unique keys. Doing that with the passwd example:

    # Read passwd files from @ARGV, outputting one record per # username. Duplicate usernames are renamed to be unique my %users; while (<>) { $user = split ":",$_,1; # next if exists $users{$user}; $_ = "a$_" , redo if exists $users{$user}; print; $users{$user} = 1; }
    The $_ .= "a" , redo statement that replaces the next appends "a" to the incoming line and then reprocesses it. I decided to reprocess it rather than just add "a" because if I had three user "foo" in the input files, I wouldn't want to get users "foo", "afoo", and "afoo", I'd want "foo", "afoo", "aafoo".

    I hope this helps.

RE: Search for dupe && append char if found
by Limo (Scribe) on Aug 22, 2000 at 08:41 UTC
    I forgot to add one additional part of the problem: how will the program know which string to modify?
      Thanks! I'm going to test that this afternoon. What I meant by "..which string...", was: <CODE> string 1 = aaa.bb.c 0/0 17 12345 string 2 = aaa.bb.c 12/12 17 12345 Just wondering which string would contain the modified field. eg: "aaa.bb.c.d" <\CODE>