4

我得到了这个 perl 示例,它应该演示sysopenand printf,但到目前为止它只演示了 die。

#! /usr/bin/perl  
$filepath = 'myhtml.html';
sysopen (HTML, $filepath, O_RDWR|O_EXCL|O_CREAT, 0755) 
    or die "$filepath cannot be opened.";
printf HTML "<html>\n";

但是当我执行代码时它只是dies。

myhtml.html cannot be opened. at file_handle.pl line 7.

myhtml.html不存在,但它应该是由O_CREAT标志创建的。不应该吗?


编辑

我已经编辑了代码以包含关于use strict和的建议$!。下面是新代码及其结果。

#! /usr/bin/perl
use strict; 
$filepath = "myhtml.html";

sysopen (HTML, '$filepath', O_RDWR|O_EXCL|O_CREAT, 0755) 
    or die "$filepath cannot be opened. $!";
printf HTML "<html>\n"; 

输出,由于use strict,给了我们一大堆错误:

Global symbol "$filepath" requires explicit package name at file_handle.pl line 3.
Global symbol "$filepath" requires explicit package name at file_handle.pl line 5.
Bareword "O_RDWR" not allowed while "strict subs" in use at file_handle.pl line 5.
Bareword "O_EXCL" not allowed while "strict subs" in use at file_handle.pl line 5.
Bareword "O_CREAT" not allowed while "strict subs" in use at file_handle.pl line 5.
Execution of file_handle.pl aborted due to compilation errors.

编辑 2

根据大家的建议和帮助,这里是最终的工作代码:

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

my $filepath = "myhtml.html";

sysopen (HTML, $filepath, O_RDWR|O_EXCL|O_CREAT, 0755) 
    or die "$filepath cannot be opened. $!";
printf HTML "<html>\n"; 
....
4

3 回答 3

11

O_RWDR, O_EXCL, 和O_CREAT都是Fcntl模块中定义的常量。放线

use Fcntl;

靠近脚本顶部。

于 2012-08-31T01:56:41.193 回答
8

Lots of issues here:

  • Always put use strict; at the top of your program. That would provide a clue.
  • The reason the sysopen failed is in the $! variable. You should generally include it in any die message.
  • As the sysopen entry in man perlfunc explains, the various O_* constants are exported by the Fcntl module. You need to use that module if you want those constants defined. As it is, you're character-wise or-ing together the strings "O_RDWR", "O_EXCL", and "O_CREAT", resulting in another string that sysopen doesn't know what to do with. use strict would prevent this from happening.
于 2012-08-31T01:47:51.867 回答
1

myhtml.html文件可能已经存在。这可能是因为脚本的先前执行创建了它。如果文件存在,该O_EXCL标志将导致sysopen失败。文档中的相关引用sysopen

在许多系统中,该O_EXCL标志可用于以独占模式打开文件。这不是锁定:排他性意味着如果文件已经存在,则sysopen()失败

于 2012-08-31T01:47:07.530 回答