lately i've become very careful not to pollute namespaces. this is sometimes hard to remember when using file and directory handles. normally, these are created inside the open statement, like open( FH, $file ) or die '...'; this is bad practice, because there are side-effects that some may not fully understand, and stricture rules don't apply to handles.

in the past, i've advocated the use of FileHandle to deal with scoping and stricture issues. i still use FileHandle, but i've come up with another way to avoid namespace pollution -- anonymous subroutines. it doesn't solve stricture problems, but i don't use strict in CGI production code anyway -- it speeds things up quite a bit. i do, and always will, use strict in development (please do the same!)

attached is a snippet for extracting files from a directory. notice the use of an anonymous subroutine, including passed parameters. i localize the handle within the sub, do my processing, and return an array -- and no messy namespace clutter to worry about later.

my $dir = '/path/to/files'; my @files = sub{ local *DH; opendir( DH, $_[0] ) or die 'Cannot open ' . $_[0]; return grep { -f $_ } readdir(DH); }->( $dir );

In reply to localizing handles with anonymous subroutines by particle

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.