in reply to Re^6: Macro in perl code?
in thread Macro in perl code?

It sounds like you have a limited number of conditions (the different levels of verbosity), so you could something like the following:

use constant MAX_VERBOSITY => 5; sub vprint { # Or whatever. our $msg; local *msg = \($_[0]); print("$msg\n"); } BEGIN { my $verbosity = $ARGV[0] || 0; # Or whatever my $eval = ''; for (1..MAX_VERBOSITY) { $eval .= ($_ <= $verbosity ? "*vprint$_ = \&vprint;\n" : "use constant vprint$_ => 1;\n" ); } eval $eval."1;\n" or die $@; } vprint1("msg1"); # Optimized away if arg is < 1 vprint2("msg2"); # Optimized away if arg is < 2 vprint3("msg3"); # Optimized away if arg is < 3 vprint4("msg4"); # Optimized away if arg is < 4 vprint5("msg5"); # Optimized away if arg is < 5

Update: Ah woops! There'll be a prototype mismatch. The best you can do (without playing with the opcode tree) is:

use constant MAX_VERBOSITY => 5; BEGIN { my $verbosity = $ARGV[0] || 0; # Or whatever my $eval = ''; for (1..MAX_VERBOSITY) { my $allow = ($_ <= $verbosity) ? 1 : 0; $eval .= "use constant V$_ => $allow;\n"; } eval $eval."1;\n" or die $@; } sub vprint { # Or whatever. our $msg; local *msg = \($_[0]); print("$msg\n"); } vprint("msg1") if V1; # Optimized away if arg is < 1 vprint("msg2") if V2; # Optimized away if arg is < 2 vprint("msg3") if V3; # Optimized away if arg is < 3 vprint("msg4") if V4; # Optimized away if arg is < 4 vprint("msg5") if V5; # Optimized away if arg is < 5

Tested

>perl -MO=Terse 645574.pl 3 LISTOP (0x1986d80) leave [1] OP (0x1986864) enter COP (0x1986da4) nextstate UNOP (0x1986e00) entersub [2] UNOP (0x1986e3c) null [141] OP (0x1986e20) pushmark SVOP (0x1986e60) const [7] PV (0x182ff6c) "msg1" UNOP (0x1986e80) null [17] PADOP (0x1986ea0) gv GV (0x191a7f4) *vprint COP (0x1986c64) nextstate UNOP (0x1986cc0) entersub [4] UNOP (0x1986cfc) null [141] OP (0x1986ce0) pushmark SVOP (0x1986d20) const [8] PV (0x191a7d0) "msg2" UNOP (0x1986d40) null [17] PADOP (0x1986d60) gv GV (0x191a7f4) *vprint COP (0x1986b24) nextstate UNOP (0x1986b80) entersub [6] UNOP (0x1986bbc) null [141] OP (0x1986ba0) pushmark SVOP (0x1986be0) const [9] PV (0x191a7b8) "msg3" UNOP (0x1986c00) null [17] PADOP (0x1986c20) gv GV (0x191a7f4) *vprint COP (0x19869e4) nextstate OP (0x1986a20) null [5] COP (0x19868a4) nextstate OP (0x19868e0) null [5] 645574.pl syntax OK >perl -MO=Terse 645574.pl 3 msg1 msg2 msg3

I'm betting this is the fastest you'll get.