【发布时间】:2013-04-22 04:53:07
【问题描述】:
我正在解析一个文件,然后从中创建多个输出文件。我想将输出文件保存在执行 perl 脚本的同一文件夹中的特殊目录中。如果该目录已经存在,则将文件放在该目录中。如果用户没有 sudo 权限,则在当前工作目录中创建文件。
use strict; use warnings;
sub main {
my $directory = "pwd/test.pl_output";
unless(mkdir $directory) {
return 0; # unable to create directory (it either already exists
# or you don't have sudo privileges)
} else {
return $directory
}
}
if ( my $PATH = main() ){
open(my $fh, '<', 'input.txt') or die $!;
open(my $output, '+>', $PATH.'/output.txt') or die $!;
} else { # create the output file as usual
open(my $fh, '<', 'input.txt') or die $!;
open(my $output, '+>', 'output.txt') or die $!;
}
print "All done! Please look in \$output\n";
在脚本的最后,在我解析并处理完文件后,我想在 shell 提示符下打印出以下内容:
All done! Please look in 'output.txt' for the output.
如果输出文件在新目录中,我想打印以下内容:
All done! Please look in 'output.txt' in the directory '~/path/to/output.txt' for the output.
我的代码不起作用。
【问题讨论】:
-
我不习惯 perl,但我在这里有一个问题,
'$PATH/output.txt'在这个 $PATH 中,它会被'中的值替换吗? -
abasu 这是另一个很好的收获。单引号不插入。我怀疑我们没有看到实际的复制粘贴代码。
-
我知道create a directory in perl 是可能的。但我不知道我正在尝试做的其余部分是否可行。
-
有可能。但是您描述的逻辑比您显示的代码更复杂。换句话说,您的条件并没有处理您提到的所有条件。而且您对'pwd'的使用不正确。只需使用 FindBin 模块,可执行文件的路径将在
$FindBin::Bin。
标签: perl bash unix sudo file-handling