开发者

How can I use macros in Perl?

How do I use macros in Perl, like I d开发者_Python百科o in C?

Example:

#define value 100 
print value; 

I want to get the output as 100.


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

Some people like:

use constant value => 100;
print value;

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";.

The "Best Practices" crowd like:

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

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


Perl is not C. You would be much better served by learning the corresponding Perl idioms (such as the already mentioned use constant value => 100) than by trying to drag C idioms into Perl.


For constants, the common way is to use a constant subroutine that will get inlined by the compiler:

use constant value => 100;

or

sub value () {100}


Try the following:

macro.pl

    use strict;
    use warnings;
    #define a 10;
    print a;

And run this code using -P switch.

Example: perl -P macro.pl

And use the module Filter::cpp also.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜