Looking at the code you just posted (thanks for that), I think the problem is that you left out the "chomp;" when reading the records in from the input file. Why did you leave that out? It's pretty important, because without that, every "parent" srting will include the "\r\n" ("CRLF") line-termination characters, and will therefore never match a "child" string (because the child never includes "\r\n" at the end). Please try adding "chomp;" as the first line of the while loop when reading in the data, and see if that helps.
Apart from that, when I put your five lines of sample data (thanks for that) into my original code, it came out in this order:
A1-4100|A1
A1-4100-YZX-002|A1-4100
A1-4100-YZX-002-01|A1-4100-YZX-002
A1-4200|A1
A1-4200-ABC-001|A1-4200
which is just like the one you said would be okay. It might also come out as:
A1-4200|A1
A1-4200-ABC-001|A1-4200
A1-4100|A1
A1-4100-YZX-002|A1-4100
A1-4100-YZX-002-01|A1-4100-YZX-002
and that should also be acceptable. If you got something other than those two possible outputs, it's probably because you forgot to "chomp;" the input, or maybe there are spurious other whitespace characters that you weren't aware of.
As for the initial "TOP" record, are you sure you have that worked out fully? Would it be the case that every top-level parent (identified as such in my script) needs its own "top-level-string|TOP" record? If so, it would be easy to modify the code to make sure this is done for each of the top-level parents -- just add a print statement print "$parent|TOP\n"; as the first thing in the main "for" loop.
I went ahead and did that on my own copy of the script, and ran it on the huge input sample that you posted above; adding the "TOP" lines like that actually makes it easier to inspect the output for correctness, as follows:
Use the unix "grep -n" command (there are perl versions posted at the Monastery and elsewhere -- e.g. here's mine: grepp -- Perl version of grep) to get the line numbers containing "TOP". Then, for any of those "top-level children", check the line numbers containing "\|top-level-string$". All the latter line numbers should be higher/later in the file than the corresponding TOP line. |