monkfan has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I have this snippet (credit Aighearach) that try to open files under subdirectory 'mysubdir'
and then stored them into a hash with filename as key and its content as values.
#!/usr/bin/perl -w use Data::Dumper; use strict; my $mydir = 'mysubdir\*'; my @filear = glob($mydir); my %hash = make_hash(@filear); sub make_hash { (local $/)=undef; my (@files,%hash); @files = @_; foreach my $file ( @files ) { open( my $fh, $file ) or next; $hash{$file} = <$file>; # This line gives "unopened filehandle wa +rning" }; return %hash; } print Dumper \%hash;
However, instead of giving the file contents as its values, it gives "undef" instead, like this.
$VAR1 = { 'mysubdir\\file1.txt' => undef, 'mysubdir\\file2.txt' => undef };
Please advice what's wrong with my code above.
Regards,
Edward

Replies are listed 'Best First'.
Re: Unopened Filehandle Problem
by steves (Curate) on Nov 06, 2004 at 16:38 UTC

    $file is the file name. You need to read from the file handle ($fh).

Re: Unopened Filehandle Problem
by zentara (Cardinal) on Nov 07, 2004 at 13:11 UTC
    Here's another tip concerning filehandles in hashes:

    #To use a hash value as a filehandle you need to add #another set of braces to create a block around it: print { $fh{$record[0]} } $_; #See print in perlfunc. ######################################################

    I'm not really a human, but I play one on earth. flash japh