#!/usr/bin/perl -w use strict; use Data::Dumper; my @AoA = ( [ qw(AAA BUY 98 0) ], [ qw(BBB SEL 27 1) ], [ qw(FFF BUY 43 4) ], [ qw(AAA SEL 98 0) ], [ qw(CCC SEL 98 0) ], ); my %directive_for; push @{ $directive_for{$_->[0]}{$_->[2]}{$_->[3]} }, $_->[1] for @AoA; my @grouped; for my $i (keys %directive_for) { for my $j (keys %{$directive_for{$i}}) { for my $k (keys %{$directive_for{$i}{$j}}) { push @grouped, [ $i, $directive_for{$i}{$j}{$k}, $j, $k ]; } } } print Dumper(\@grouped);