cr_ashok has asked for the wisdom of the Perl Monks concerning the following question:

I want to use preproceesor directive conecpt in perl similar to that of C. So based upon the directive only certain part of the code alone will execute. Is it possible?

Replies are listed 'Best First'.
Re: Using Pre-processor directive in Perl
by Corion (Patriarch) on May 13, 2005 at 07:05 UTC

    Yes, it is possible. But no, you should not use it.

    There are two common ways of making code not run. One is to comment out code blocks with POD sections, but that cannot be done dynamically, and the other is to declare a subroutine as the toggle:

    sub DEBUG() { 0 }; ... if (DEBUG) { print "We are here <--"; };

    There is (almost) no overhead with this method because Perl optimizes constant subroutines away.

Re: Using Pre-processor directive in Perl
by salva (Canon) on May 13, 2005 at 07:11 UTC
    you can use source filters for that, see perlfilter manual page... though most of the time it is a bad idea to do so. As Corion has already suggested, a better alternative is to use "if (Constant) {...}" constructions.
Re: Using Pre-processor directive in Perl
by spurperl (Priest) on May 13, 2005 at 10:26 UTC
    I just want to add that there's a fundamental difference between C and Perl that makes "code disabling" preprocessor directives in Perl unnecessary.

    C is a compiled language, and preprocessor is for the *compiler*. What's #ifdef-ed out won't show up in the compiled code at all. This can boost performance and reduce the executable file size especially for multiplatform apps.

    Perl is not compiled, at least not in the sense C is, so it doesn't need such complications. A simple if (0) is good enough to exclude code from running. No preprocessor directive will make your code smaller to carry aroung.

Re: Using Pre-processor directive in Perl
by blazar (Canon) on May 13, 2005 at 08:45 UTC
    my %answer = ( possible => '-P', # See 'perldoc perlrun' recommended => 0 ); # Ditto as above!
Re: Using Pre-processor directive in Perl
by Zaxo (Archbishop) on May 14, 2005 at 06:25 UTC

    There is perl's -P flag; see perlrun. Better to learn the perly way of doing things.

    After Compline,
    Zaxo