Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

localizing handles with anonymous subroutines

by particle (Vicar)
on Jun 10, 2002 at 13:09 UTC ( #173106=snippet: print w/ replies, xml ) Need Help??

Description: 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 );
Comment on localizing handles with anonymous subroutines
Download Code
Re: localizing handles with anonymous subroutines
by jmcnamara (Monsignor) on Jun 10, 2002 at 13:30 UTC

    Is there an advantage of this method over do?
    my @files = do { local *DH; opendir( DH, $dir ) or die 'Cannot open ' . $dir; grep { -f $_ } readdir(DH); };

    --
    John.

      yes, there's a huge advantage. do is not a subroutine. it cannot take parameters. just try to do this!

      my %dispatch = ( sub_get_files => sub{ # takes one arg local *DH; opendir( DH, $_[0] ) or die 'Cannot open ' . $_[0]; return grep { -f $_ } readdir(DH) }, ); my @files = $dispatch{sub_get_files}->( $dir );
      do executes immediately, and would spit the results into the hash. icky.<p

      ~Particle *accelerates*

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://173106]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2014-12-22 05:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (110 votes), past polls