It’s the first time I’ve used a hash in Perl, and I’m stuck in a weird problem. What I’m trying to do is after I backup files in a directory, I use a Perl program to check if all files appearin the log file. So I had the following code:
our (%missing_files) = (); # global definition on the top of the program
... do something ...
sub CheckTarResult {
my (@dir_list) = (); # dir list
my (@file_list) = (); # will be filled with all file names in one dir
my ($j) = "";
my ($k) = ""; # loop variable
my ($errors) = 0; # number of missing files
... do something ...
foreach $j (@dir_list) {
@file_list = `ls $j`;
foreach $k (@file_list) {
$result = `cat $logfile | grep $k`;
if ($result eq "") {
$errors++;
$missing_files{$j} = ${k};
}
}
@file_list = ();
}
... do something ...
my($dir) = "";
my($file) = "";
while ( ($dir, $file) = each(%missing_files) ) {
print $dir . " : " . $file;
}
I made an empty log file to do the test, the expecting result should give me all files missing, but somehow “missing_files” only stores the last missing file in each dir. The logic seems to be straightforward, so what am I missing here?
Edit:
I used the advice from @Borodin, and it worked. But in order to print the content of an array reference, we need to loop through elements in the array. The code after the change looks like the following:
... everything before is the same ...
push @{$missing_files{$j}}, ${k}; # put elements in dictionary
# in the print statement
while( ($dir, $file) = each(%missing_files) ) {
for $i ( 0 .. $#$file ) { # $#$file represents the array size by reference
print $dir . " : " . ${$file}[i];
}
}
Perl hash values can contain only a single scalar. If you want to store a list of things then you must make that scalar an array reference. To do that, change the line
to