my $desired_page_count = 10; # Structure holding all the different page layouts. ('l' = Landscape, 'p' = Portrait) my $pages = { ll => '01', pp => '02', lp => '03', pl => '04', lpp => '05', pll => '06', plp => '07', lpl => '08', lll => '09', ppp => '10', ppl => '11', llp => '12', ppll => '13', llpp => '14', }; my $regex = join '|', keys %$pages; print "Regex is $regex\n"; my $photos = "llppllpplpppllplpplpplpllplpll"; my $pages_left = $desired_page_count - 1; while ($photos =~ s/^($regex)(?=(?:$regex){$pages_left}$)//) { print "$1\n"; # Reorder the regex so that the most-recently-used is the last option $regex = join '|', (grep {$_ ne $1} keys %$pages), $1; --$pages_left; } print "Failed to layout the whole set: $photos does not match $regex\n" if $photos;