Specify an array variable in the path for opening a new file

时间:2016-03-17 19:37:11

标签: perl filehandle

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?

1 个答案:

答案 0 :(得分:6)

没有看到您的错误消息,我非常清楚错误。

foreach my $dir (@listofdirs) {
    open (my $OUTFILE, '>', "$dir/$dir.txt") or die; 
    ...
}

我猜测@listofdirs包含/foo/barfoo/bar/baz/之类的内容,因此"$dir/$dir.txt"会创建一些有趣的文件路径。

$dir                      "$dir/$dir.txt"
/foo/bar                  /foo/bar//foo/bar.txt
foo/bar/                  foo/bar//foo/bar/.txt
foo/                      foo//foo/.txt

其中大多数因各种原因无法运作。 /foo/bar//foo/bar.txt将要求目录/foo/bar/foo/已存在。 foo/bar//foo/bar/.txt是无效路径。

无论如何,

"$dir/$dir.txt"是一个有趣的构造。你确定那是你的意思吗?

要弄清楚出了什么问题,您可以在错误消息中添加一些信息。传统的方法是在每次open来电时尽快写出来。

foreach my $dir (@listofdirs) {
    open (my $OUTFILE, '>', "$dir/$dir.txt")
        or die "Can't open '$dir/$dir.txt': $!";
    ...
}

现在,您将看到它尝试打开的内容,以及失败的原因(包含在$!中)。这很快就会变得令人厌烦和不一致,所以最好让autodie为你做这件事。

# at the top of your code along with things like "use strict"
use autodie;

...

foreach my $dir (@listofdirs) {
    open (my $OUTFILE, '>', "$dir/$dir.txt");
    ...
}