【问题标题】:Error when opening a file located in the same directory打开位于同一目录中的文件时出错
【发布时间】:2012-11-26 13:42:29
【问题描述】:

我刚开始学习 Perl,但在打开与我的程序位于同一目录中的文件时遇到问题。

#!/usr/bin/perl -w

$proteinfilename = 'NM_021964fragment.pep';

open(PROTEINFILE, $proteinfilename) or die "Can't write to file '$proteinfilename' [$!]\n";

$protein = <PROTEINFILE>;

close(PROTEINFILE);

print "Essa é a sequência da proteína:\n";
print $protein, "\n";

exit;

当我指定文件的目录时,从“NM_021964fragment.pep”更改为“/Users/me/Desktop/programa/NM_021964fragment.pep”,程序运行。但是即使没有我指定目录,它也不能工作,因为程序和文件在同一个文件夹中?

【问题讨论】:

  • give'./NM_021964fragment.pep' 试试看。
  • 你的脚本适合我。你运行了这个确切的代码吗?你的操作系统是什么?
  • 另外,我假设您的脚本因错误No such file or directory 而死掉?报告确切的错误是个好主意,以供将来参考,即使对您来说很明显,但对其他人来说并不明显。
  • 我正在使用 OSX。是的,我得到的错误是:Can't write to file 'NM_021964fragment.pep' [No such file or directory]

标签: perl file directory


【解决方案1】:

相对路径是相对于当前工作目录的,而不是脚本的目录。当脚本起作用时,它们恰好是相同的。但正如您所发现的,情况并非总是如此。您可以使用以下方法来实现您描述的行为:

use Cwd         qw( realpath );
use Path::Class qw( file );

my $script_dir = file(realpath($0))->dir;
my $input_file = $script_dir->file('NM_021964fragment.pep');

【讨论】:

    【解决方案2】:

    如果您正在执行简单的文件读取,您可以使用&lt;&gt; 菱形运算符为简单起见。

    use strict;
    use warnings;
    
    my $protein = <>;
    print "Essa é a sequência da proteína:\n";
    print "$protein\n";
    

    然后像这样使用脚本:

    perl script.pl NM_021964fragment.pep
    

    这将强制您使用正确的路径,假设您在运行脚本时使用选项卡自动完成功能。

    以这种方式使用命令行参数有些不安全,因为可以通过不受保护的open 命令执行任意代码。您可以使用模块ARGV::readonly 来防止此类事情发生。或者干脆使用代码本身,比较简单:

    for (@ARGV){
       s/^(\s+)/.\/$1/;    # leading whitespace preserved
       s/^/< /;            # force open for input
       $_.=qq/\0/;         # trailing whitespace preserved & pipes forbidden
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 2022-01-07
      • 2020-10-24
      • 2021-05-20
      • 2013-11-17
      • 1970-01-01
      相关资源
      最近更新 更多