use strict; my $change = 16; my @coins = reverse sort qw(2 5); my $q='1'x$change; my $solution = join'',map{qr(((?:.{$_})+))} @coins; $q = ~/^()$solution$/ or die "Error in regex construction"; { # This should maybe be done via @-, but I'm lazy: no strict; print(length(${$_})/$_, '*', $_) for (1..4) };