$str = join("\n", map { $_->[0] } sort{ $a->[1] cmp $b->[1] || $a->[2] <=> $b->[2] } map { [$_, ( split /\|/, $_ )[0,1] ] } split/\n/, $str );