How can I use macros in Perl?

前端 未结 4 1297
一生所求
一生所求 2021-01-01 05:36

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

Example:

#define value 100 
print value; 

I want to get the output as 100.

相关标签:
4条回答
  • 2021-01-01 06:02

    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.

    0 讨论(0)
  • 2021-01-01 06:10

    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}
    
    0 讨论(0)
  • 2021-01-01 06:24

    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 讨论(0)
  • 2021-01-01 06:26

    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.

    0 讨论(0)
提交回复
热议问题