gpt4 book ai didi

c - "Use"h2ph 从 C 头文件生成的 Perl 文件?

转载 作者:太空宇宙 更新时间:2023-11-04 04:38:37 25 4
gpt4 key购买 nike

h2ph 实用程序从 C 头文件生成一个 .ph “Perl 头”文件,但是使用此文件的最佳方法是什么?比如,它应该是 require 还是 use?:

require 'myconstants.ph';
# OR
use myconstants; # after mv myconstants.ph myconstants.pm
# OR, something else?

现在,我正在执行上面显示的 use 版本,因为对于那个版本,我永远不需要在常量后键入括号。我想键入 MY_CONSTANT 而不是 MY_CONSTANT(),并且在我需要常量的 Perl 文件中我有 use strictuse warnings 生效。

虽然对这个文件执行 use 有点奇怪,因为它没有声明模块名称,而且它似乎并不是特别打算成为一个模块。

我只有一个文件正在通过 h2ph 运行,而不是一百个或任何东西。

我看过 perldoc h2ph,但它根本没有提到预期导入机制的主题。

示例输入和输出:为了进一步了解背景,这里有一个示例输入文件以及 h2ph 从中生成的内容:

// File myconstants.h
#define MY_CONSTANT 42

...

# File myconstants.ph - generated via h2ph -d . myconstants.h
require '_h2ph_pre.ph';
no warnings qw(redefine misc);
eval 'sub MY_CONSTANT () {42;}' unless defined(&MY_CONSTANT);
1;

问题示例:这是一个“问题”示例,我需要使用括号来让代码使用 use strict 进行编译:

use strict;
use warnings;
require 'myconstants.ph';

sub main {
print "Hello world " . MY_CONSTANT; # error until parentheses are added
}
main;

产生以下错误:

Bareword "MY_CONSTANT" not allowed while "strict subs" in use at main.pl line 7.
Execution of main.pl aborted due to compilation errors.

结论:那么是否有更好或更典型的使用方式,就导入myconstants.ph 等文件的最佳实践而言?拉里沃尔会怎么做?

最佳答案

您应该要求您的文件。正如您所发现的,use 只接受一个裸词 模块名称,将myconstants.ph 重命名为 是错误的。 pm 后缀,以便 use 正常工作。

选择 userequire 对在代码中使用常量时是否需要括号没有影响。生成的 .ph 文件以与 constant 相同的方式定义常量。模块,在绝大多数情况下你需要的只是裸标识符。一个异常(exception)是当您使用常量作为散列键时,当

my %hash = { CONSTANT => 99 }
my $val = $hash{CONSTANT}

不起作用,因为您使用字符串 CONSTANT 作为键。相反,你必须写

my %hash = { CONSTANT() => 99 }
my $val = $hash{CONSTANT()}

您可能还想将require 包装在BEGIN block 中,如下所示

BEGIN {
require 'myconstants.ph';
}

确保这些值可用于代码的所有其他部分,包括后续 BEGIN block 中的任何内容。

关于c - "Use"h2ph 从 C 头文件生成的 Perl 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28624531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com