I have code which stores all the files handles for files in the current directory as values in a hash. The keys are the names of the files.
my %files_list; #this is a global variable.
sub create_hash() {
opendir my $dir, "." or die "Cannot open directory: $!";
my @files = readdir $dir;
foreach (@files) {
if (/.text/) {
open(PLOT, ">>$_") || die("This file will not open!");
$files_list{$_} = *PLOT;
}
}
}
Down the line I am using print statements in my code where I am facing some compilation issues.
my $domain = $_;
opendir my $dir, "." or die "Cannot open directory: $!";
my @files = readdir $dir;
foreach (@files) {
if (/.text/ && /$subnetwork2/) {
print $files_list{$_} "$domain"; #this is line 72 where there is error.
}
}
closedir $dir;
The compilation errors are below:
String found where operator expected at process.pl line 72, near "} "$domain""
(Missing operator before "$domain"?)
syntax error at process.pl line 72, near "} "$domain""
Could anyone please help me understand the fault?
first problem:
After running
create_hashsubroutine you would have%files_listfilled up with*PLOTin all keys.all
print {$files_list{$_}} "$domain";whould print into last opened file.solution:
second problem:
you don’t check that file descriptor exists before printing into it
solution:
and don’t forget about closing file handles…