For a task like this one, everything depends on your data-structure. It appears that your data consists of “lists of zero-or-more values” indexed by two keys. The first key is introduced at the beginning of each group, e.g. id1. The second is introduced with each row.
The most appropriate Perl structure, it seems to me, is: “a hashref of hashrefs of arrayrefs.” (If you happen to know that the second dimension is always contiguous integers, it might be “a hashref of arrayrefs of arrayrefs.”)
Each time you encounter a line which introduces a new key (such as id3), you will create a new hashref entry for it, and remember what it is. When you encounter a line of the other kind, the process is similar. You know that an entry for the major-key (id3) exists. So, now, check that this hashref contains the minor-key; create a new empty entry (containing an arrayref) if it doesn’t. push the new value onto this array.
Output will make heavy use of sort keys hashref.
You may need to use a sort-function in the sort clauses to ensure that comparisons are numeric.
The program is not quite straightforward, but it is uncomplicated.