i've been localizing handles with anonymous subroutines for a while now.
i think i'd write your snippet as an anonymous sub, giving it a little more muscle compared to a do block. something like:
#!/usr/bin/perl
require 5.006_001;
use strict;
use warnings;
$|++;
my %cool_funcs = (
## slurp a file to a scalar
## pass filename (as scalar)
## returns contents of file (scalar context)
slurp_to_scalar => sub{ local( *ARGV, $/ ); @ARGV = @_; <> },
## slurp one or more files to an array
## pass filename(s) (as scalar)
## returns contents of file(s) (list context)
## returns number of lines (scalar context)
slurp_to_array => sub{ local *ARGV; @ARGV = @_; <> },
);
## to use it:
## create a list of test files
my @files = @ARGV;
## get the contents to an array, and the number of lines to a scalar
my $no_of_lines = ( my @contents ) =
$cool_funcs{slurp_to_array}->( @files );
## these values match...
print $no_of_lines, $/, scalar @contents, $/;
## here's the good stuff...
print @contents;
## get file to scalar -- note extra args are ignored
my $data = $cool_funcs{slurp_to_scalar}->( @files );
## here's the file's contents...
print $data;
~Particle *accelerates*
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|