-3

For example if I have this array:

array={"a","b","c","d","a","d","b","d","z"}

I want to split it to arrays that involves the same elements by Perl.

The output should be like this:

array1={"a","a"}
array2={"b","b"}
array3={"c"}
array4={"d","d","d"}
array5={"z"}
G. Cito
  • 6,210
  • 3
  • 29
  • 42
  • I'm with @ikegami since the data-structure seems a little bit strange. Also, since it does not effect the subsequent responses you could correct the syntax of your question*i.e.* `@array = ( "a","b","c","d","a","d","b","d","z",)`; or note that it is pseudo-code. – G. Cito Apr 27 '15 at 18:32

1 Answers1

3
my @grouped;
my %indexes;
push @{ $grouped[ $indexes{$_} //= @grouped ] }, $_
   for @array;

But why would you ever need such a structure? It seems to me that all you need is the counts.

my %counts;
++$counts{$_} for @array;

You can recreate the items later if need be.

my @grouped;
push @grouped, [ ($_) x $counts{$_} ]
   for keys %counts;
ikegami
  • 367,544
  • 15
  • 269
  • 518