Although I found many posts on how to open a file in a for loop in perl, I am having a specific issue in creating a file within a directory ( which is also the array variable)-
I am opening a file using
foreach my $dir (@listofdirs) {
open (my $OUTFILE, '>', "$dir/$dir.txt") or die "$!";
, this does not create a file and gives me an error No such file or directory.
If i just use open (my $OUTFILE, '>', "$dir.txt") or die; It works and creates a file under main directory from where I execute the script.
How can I control/specify the path so that it opens a file inside each $dir variable (directory)? I am sorry if this has been addressed earlier, but I am not sure what is the right way to specify the path for the new files.
Edit -
Can I change directory where the file is being created inside the loop and assign it the $dir variable value everytime?
$dir?or die;isn't going to tell you what went wrong. You could addor die "Failed to open $dir/$dir.txt: $!"to everyopencall... or you can remove theor dieand instead adduse autodieat the top of your program. Now if file functions likeopenfail they will automatically die with a descriptive error message.open (my $OUTFILE, '>', "$dir/$dir.txt")lineuse autodie;to get the real error message oropen (my $OUTFILE, '>', "$dir/$dir.txt") or die "$!";