$str = '1000000000000100000000000000100'; while (($pos = index($str, '1', ($pos ? $pos + 1 : 0))) >= 0) { push(@length, length($str) - $pos - 1); $pos++; } for (1 .. @length) { print "\$var$_ would get $length[$_-1] bits\n"; }