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

I have two arrays of text and XML tags and I'm trying to figure out which match up. Many of the tags are nested in other tags and may or may not exist at all in the other array For example
@array1 = ("Here ","<Tag Id=1>","is","</Tag>"," an ","<Tag Id=2>", "example that ","<Tag Id=3>","I","</Tag>"," just made","</Tag>") @array2 = ("<Tag Id=7>","Here is","</Tag>"," an ","<Tag Id=8>", "example that I just made","</Tag>")
Or shown joined up for easier reading
Array 1 = Here <Tag Id=1>is</Tag> an <Tag 2>example that <Tag Id=3> I</Tag> just made</Tag> Array 2 = <Tag Id=7>Here is</Tag> an <Tag 2>example that I just made</Tag>
As you can see (or perhaps not, my example isn't great) tag2 in @array1 matches tag 8 in @array2 while the other tags simply don't match up. The way that I've been attempting to solve this at the minute is simply by tracking how much of the actual text I've been through and using a heap of if statments to determine what to do. But it is quite long, and very hard to read. I'm thinking there must must be an easier way to do this, perhaps by filtering the array in some manner so that the tags that match can be easily mapped together. Or perhaps there is no easy solution. How would all you clever perl people go about solving a problem like this?

Replies are listed 'Best First'.
Re: Matching up XML tags in 2 arrays
by ikegami (Patriarch) on Jan 15, 2007 at 06:21 UTC
    You could build a hash for each doc, where the key is the node's content, and the value is a reference to a list of ids.
    my %text1 = ( "is" => [ "1" ], "example that I just made" => [ "2" ], "I" => [ "3" ], ); my %text2 = ( "Here is" => [ "7" ], "example that I just made" => [ "8" ], ); foreach my $content (keys %text2) { next if not exists $text1{$content}; my @ids = ( (map { "text1.$_" } @{$text1{$content}}), (map { "text2.$_" } @{$text2{$content}}), ); print("\"$content\" found at ", join(', ', @ids), "\n"); }

    Building the hashes is an exercise left to the user (since it's dependant on the parser you're using).

      Wouldn't that mean that if two tags had the same content, there would be a collision?

      Eg <Tag id=1>He</Tag> Walked Like <Tag id=2>He</Tag> Talked. Then there would be a collision of some kind between the two tags containg 'He'.

      What does perl do in a situation like this? Is the first tag simply replaced by the second?

        That's why ikegami suggested using a hash of arrays. If you push a new tag ID onto the array you will be able to track all occurrences without overwriting existing data. Your example would look something like this:

        %text = ( 'He' => [ 1, 2 ], ...

        If, on the other hand, you were using a straight hash:

        %text = ( 'He' => 1, ...
        then yes, the first tag would be replaced by the second.

        You may find perldsc and our Tutorials section (specifically Data Types and Variables) helpful.