>>>>> "Gabriel" == Gabriel Aurillo <[EMAIL PROTECTED]> writes:

Gabriel> I have an array, as follows:
Gabriel> @allLines = (
Gabriel>        "line1 = value1",
Gabriel>        "line2 = value2",
Gabriel>        "line3 = value3",
Gabriel>        "!line4 = value1",
Gabriel>        "!line5 = value2",
Gabriel>        "!line6 = value3",
Gabriel>        "line7 = value7",
Gabriel>        "line8 = value8",
Gabriel>        "line9 = value9",
Gabriel>        "line10 = value10"
Gabriel> ) ;

Gabriel> How do I loop through each line with the following criteria:
Gabriel> If the line starts with a bang (!) AND the value has already
Gabriel> been "seen", skip that line AS WELL AS the line previously
Gabriel> seen. In this case, the remaining list should only have lines
Gabriel> 7 to 10 because line 4 starts with a bang AND the value is
Gabriel> equal to the value of line 1. And so on...

This is an incomplete specification.  What if a line starts with a
bang and that value has NOT been seen?  What if it's seen later?  What
delimits "lineN" from "valueN"?  Is "valueN" always in that format?
Are these actual values, or representative?  If representative, what
variation is expected?  What if values are duplicated?

Presuming a simplification, that a line always matches

  /^!?line\d+ = value\d+$/

and that a value appears only once (as a ! or non-bang line) or
twice (as a pair or non-bang then bang), I get the following code:

    @allLines = (
            "line1 = value1",
            "line2 = value2",
            "line3 = value3",
            "!line4 = value1",
            "!line5 = value2",
            "!line6 = value3",
            "line7 = value7",
            "line8 = value8",
            "line9 = value9",
            "line10 = value10"
    ) ;
    my @output = ();
    my %value_at = ();
    for (@allLines) {
      /^(!?)line\d+ = (value\d+)$/ or die;
      if ($1) { # it's a delete
        if (exists $value_at{$2}) { # and we've seen it
          $output[$value_at{$2}] = undef; # we'll remove that later
          delete $value_at{$2}; # do this only once
        } else { # we've not seen it, just include
          push @output, $_;
        }
      } else { # it's a non-delete
        push @output, $_;
        $value_at{$2} = $#output; # note location for possible delete
      }
    }
    @output = grep defined $_, @output; # flush undefs
    print "$_\n" for @output;

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<[EMAIL PROTECTED]> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to