Bill
Bill

Reputation: 1247

How can I find elements from a Perl array that match elements in a second array?

I have two arrays

@one = ("1|1|the|dog|ran", "1|2|a|x|b", "2|8|e|s|e");
@two = ("1|2|a|x|b", "1|1|down|the|street", "2|8|e|s|e");

I need to match them by the first two "|" separated elements. So that when on $one[0] the search would return $two[1].

There are millions of lines in each array so I need the fastest way to do this.

EDIT: Sorry for the confusion. I want to treat the first 2 "|" separated elements (ie. 1|2, 2|1) as a key for the array, loop through the first array and search the second array using that key to get the values in the second array. Does that help?

Upvotes: 2

Views: 273

Answers (1)

ikegami
ikegami

Reputation: 385506

- For each record in the second array,
  - Parse the record
  - Add it to a hash keyed by the first two fields.

- For each record in the first array,
  - Parse the record
  - Look in the hash for a record with the appropriate key.
  - If there is one,
    - Do something with it.

Upvotes: 4

Related Questions