how can i read multiple files in perl a开发者_C百科nd store them in a hash?
Thanks.
my %data;
my @FILES = @ARGV;
# or maybe @FILES = glob("some/directory/*.ext");
Since this is Perl, there are many ways to do it.
# 1. Open and load each file
foreach my $file (@FILES) {
local $/ = undef;
open my $fh, '<', $file;
$data{$file} = <$fh>;
}
# 1b. Using map
%data = map {
local $/=undef;
open my $fh, '<', $file;
my $data = <$fh>;
$_ => $data
} @FILES;
# 2. Leverage your operating system
foreach my $file (@FILES) {
$data{$file} = qx(/bin/cat "$file");
}
# 3. Use a module
use File::Slurp;
foreach my $file (@FILES) {
$data{$file} = File::Slurp::slurp($file);
}
# 3b, using map
use File::Slurp;
%data = map { $_ => File::Slurp::slurp($_) } @FILES;
See this perlfaq entry: How can I read in an entire file all at once?
A hash can be created like this:
my %hash = (
filename => $file_content,
# ...
);
my %data;
foreach my $fn (@ARGV) {
open (my $IN, $fn) or die "couldn't open $fn: $!";
$data{$fn} = join "", <$IN>;
close $fn;
}
foreach my $key (keys %data) {
print "File $key:\n$data{$key}\n\n\n";
}
The code iterates over a list of file names, in this case passed in as command line arguments in @ARGV. For each filename, it opens a file handle and reads from it in array context, which loads each line of the file as an element of the array. In this case, we're reading to an anonymous array which is passed into join. Join glues the elements of the array together, in this case with the empty string as a separator. The result, one string with the entire file contents, is then stored in the hash with the filename as the key. The second loop just prints the results.
Note that for large files, this is a good way to run yourself out of memory fast. Think about ways to process your data in a streaming mode.
Assuming all the files are in @ARGV
, for instance if they're commandline arguments, you can iterate over them all like this:
@array = ();
while (<>) {
push @array, $_;
# or any other manipulation on the lines
# for instance extracting a key and value from
# the line and putting them into a hash
}
精彩评论