We can make a sub-routine out of this logic, like this,

Code: Perl
sub getFreeFilename
 {
     my $counter = 0;
     my $file_name = "";
     do {
         $file_name = sprintf("%s%s%s.html",$$,$^T,$counter++);
     } while -e $file_name;
 
     return $file_name;
 }