如何从文本文件中获取perl脚本来执行命令?

dff*_*dff 1 printing perl

#!/usr/bin/perl
use strict;
use warnings;

my $fileName = "fileName.txt";

if (-e $fileName) {
        my $read = open($fileName);
        print "File exists and has been read\n";
        eval $read;
        unlink $fileName;
}
else {
        print "File does not yet exist\n";
}
Run Code Online (Sandbox Code Playgroud)

这就是我到目前为止所拥有的.此脚本的目标是检查文件是否存在,然后在文件存在时执行文件中的命令,但是每当我尝试运行此脚本时,我都会收到一条错误消息,指出我无法使用该字符串" fileName.txt"作为符号引用,但即使我在文件名中硬编码而不是将其设置为变量,我收到一条错误,指出$ fileName需要一个显式的包名.

Sla*_*ade 5

然后啜饮文件 eval

你没有open正确使用.Open旨在创建文件句柄,但您仍需要从文件句柄中读取以加载内容.

以下文件像perlfaq5中建模一样 -文件- 如何一次读取整个文件?

my $code = do {
    open my $fh, '<', $fileName or die $!;  
    local $/;
    <$fh> 
};
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用以下模块File::Slurp:

use File::Slurp qw(read_file);

my $code = read_file($fileName);
Run Code Online (Sandbox Code Playgroud)

然后你可以eval像你最初那样加载代码:

eval $code;
Run Code Online (Sandbox Code Playgroud)

使用执行外部Perl代码 do EXPR

另一方面,您可以执行外部perl代码,而无需使用加载文件的内容do EXPR.您可以使用perldoc -f do以下方法查看文档:

哪个会让你写的do $fileName.

(请注意,do EXPR一样的do BLOCK在第一个代码示例中使用.)

do EXPR但是有弱点; 如果你告诉它,它将多次编译和执行同一个文件.它可以用于快速和脏脚本,但是Perl提供的更安全和更强大的机制是使用requireuse加载的模块(注意如何是一个更强大的版本,并且就像一个包装器,也可以从中导入东西)模块).requiredo FILEuserequire