0

我正在解析一个文件,然后从中创建多个输出文件。我想将输出文件保存在执行 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.

我的代码不起作用。

4

2 回答 2

3

您现有的代码存在几个严重的问题。一个是您pwd在双引号字符串内部的使用。那是行不通的。您可以在反引号内使用pwd并捕获输出,但不能在双引号文字内使用。

另一个问题是您的代码逻辑没有达到描述您希望如何优雅地降级目的地的复杂性。

以下代码片段将首先在可执行文件的目录中查找名为“special”的目录。如果它不存在,它将尝试创建它。如果创建失败(可能是因为权限问题),它接下来会在用户当前的工作目录中寻找一个名为“special”的目录。如果它不存在,它将尝试创建它。如果失败,它将以描述性消息结束。

如果它超过了这一点,那么“特殊”目录要么是预先存在的,要么是沿着允许的路径之一创建的。接下来,打开文件。如果打开输出文件失败,我们就死了。否则,继续并可能写入文件。然后关闭输入和输出文件。最后,打印可以找到输出文件的路径。

use strict;
use warnings;

use FindBin;
use File::Path qw( make_path );

my $special_dir = 'special';
my $filename    = 'my_file.txt';


my $bin = $FindBin::Bin;

my $path;


if( not defined( $path = get_path( "$bin/$special_dir", "./$special_dir" ) ) ) {
  die "Unable to find or create a suitable directory for output file.";
}

my $output_filename = "$path/$filename";


open my $in_fh, '<', 'input.txt' or die $!;
open my $out_fh, '+>', $output_filename or die $!;

# Do whatever it is you want to do with $in_fh and $out_fh....

close $out_fh or die  $!;
close $in_fh  or warn $!;

print "All done! Please look in $output_filename for the output.\n";



sub get_path {
  my @tries = @_;
  my $good_path;
  for my $try_path ( @tries ) {
    if( -e $try_path and -d _ and -w _ ) {          # Path exists. Done.
      $good_path = $try_path;
      last;
    }
    elsif( eval { make_path( $try_path ); 1; } ) {  # Try to create it.
      $good_path = $try_path;                       # Success, we're done.
      last;
    }
  }
                                                    # Failure; fall through to
                                                    # next iteration.  If no
                                                    # more options, loop ends
                                                    # with $path undefined.
  return $good_path;
}

我正在使用 Perl 模块 FindBin 来定位可执行文件。File::Path 用于创建目录。

于 2013-04-22T06:35:27.457 回答
0

过去有几次,我发现将 perl 脚本与 Shell 脚本一起用于此目的会更好。用于解析的 Perl 脚本和用于文件夹处理的 shell 脚本。并轻松地将 perl 脚本包含在 shell 脚本中。它会更容易和方便。

于 2013-04-22T05:33:22.060 回答