You're indentation is all over the place. If we fix that and analyze just your misbehaving subroutine:

sub dirname { my $word = "site"; my $counter = 1; my $flag = 1; while ($flag) { my $name = "$word" . "_" . "$counter"; if ( -e -d $name) { $counter++; next; } else { mkdir $name, 0755 or warn "Cannot make dir $name: $!"; $flag = '0'; } print "$name \n"; $name; # "Useless use of private variable in void context" } }
we see that Perl helpfully warns us that the $name; line above is useless. If we fix that by replacing the useless $name with return $name and change -e -d $name to -e $name and eliminate the now unnecessary $flag we will have a non-looping subroutine that kinda works. Note however that aaron_baugher has already shown us a much cleaner way to code your subroutine and his version is preferred to patching your original code.

Having said that, this sort of code is tricky to get right, and race conditions and security exploits abound -- which is why Perl provides the File::Temp module. If you tell us your requirements for these "temporary" directories (and files?) we could offer more advice on this and I suspect the core File::Temp module could be employed to satisfy your requirements.

Other random stylistic suggestions:


In reply to Re: getting a while loop to terminate (File::Temp) by eyepopslikeamosquito
in thread getting a while loop to terminate by Aldebaran

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.