my @data = qw( 000- 0101 011- 1-0- ); my @res = map expand( $_), @data; print "@res\n"; sub expand { my $template = shift; my $n_dashes = $template =~ tr/-//; my $mask; # ones where - was, else 0 ( $mask = $template) =~ tr/01-/001/; my $val; # zeroes where - was, else unchanged ( $val = $template) =~ tr/01-/010/; $_ = oct "0b$_" for $mask, $val; # transform to numeric my @coll = $val; push @coll, $val = increment_masked( $val, $mask) for 1 .. 2**$n_dashes - 1; @coll; } # Increment the combined unmasked bits as a single binary number, # leaving masked bits alone. Masked bits are indicated by a 0-bit in # the mask, unmasked bits by 1 sub increment_masked { my ( $x, $mask) = @_; ( ( ($x | ~$mask) # fill masked bits with 1 + 1 # increment (carry will jump over... # masked stretches) ) & $mask) # clear masked bits, leaving... # incremented bits alone | ($x & ~$mask); # restore masked bits from $x }