#!/usr/bin/perl -w use strict; my $string = '9999'; # Starting with nines simplifies the loop my %seen = ( $string => 1 ); my $seen = 1; while ($seen < 10000) { for (0 .. 9) { my $candidate = substr($string, -3) . $_; next if $seen{$candidate}; $string .= $_; $seen{$candidate} ++; $seen++; last; } } print $string, "\n";