#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $text = 'XYYYZ'; my @source; push @{$source[$1 ? 0 : $2 ? 1 : 2]}, $& while $text =~ /(X)|(Y)|(Z)/g; print Dumper \@source; __END__ $VAR1 = [ [ 'X' ], [ 'Y', 'Y', 'Y' ], [ 'Z' ] ];