use strict; use warnings; $\ = "\n"; my %label = ( 3 => 'fizz', 5 => 'buzz', ); my $end = 100; my %queue; $queue{0}{$_} = 1 for keys %label; my $i = 0; while (1) { my($n) = sort { $a <=> $b } keys %queue; # "shift" the next generated number while ( $i < $n ) { print $i++; } # print any "non-special" numbers before it last if $i++ > $end; my @why_its_special = sort { $a <=> $b } keys %{ delete $queue{$n} }; print @label{ @why_its_special }; $queue{ $n + $_ }{$_} = 1 for @why_its_special; # generate the next succeeding number(s) }