如何在 Perl 中使用宏? [英] How can I use macros in Perl?

查看:52
本文介绍了如何在 Perl 中使用宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在 Perl 中使用宏,就像在 C 中一样?

How do I use macros in Perl, like I do in C?

示例:

#define value 100 
print value; 

我想将输出设为 100.

I want to get the output as 100.

推荐答案

如果您只想定义常量(如您的示例)而不是完整的宏,有几种 perl 方法可以做到这一点.

If you just want to define constants (like your example) rather than full macros, there are a couple of perl ways to do this.

有些人喜欢:

use constant value => 100;
print value;

请注意,value"是一个子程序,而不是变量".这意味着你不能在字符串中插入它,所以你必须这样做.print "The value is ".value."\n";.

Note that 'value' is a subroutine, not a 'variable'. This means you cannot interpolate it in strings so you have to do. print "The value is ".value."\n";.

最佳实践" 喜欢:

use Readonly;
Readonly my $value => 100;
print $value;

但是,与常量不同,Readonly 不是核心 perl 发行版的一部分,因此需要从 CPAN 安装.

However, unlike constant, Readonly is not part of the core perl distribution and so needs to be installed from CPAN.

这篇关于如何在 Perl 中使用宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆