in reply to Re^2: Unable to assign value to constants using ternary operator
in thread Unable to assign value to constants using ternary operator

Force that stuff to happen at compile time using BEGIN:

my $word64; BEGIN { my $hw = `uname -i`; $word64 = 1 if $hw =~/x86_64|ia32e/; } use constant CRACKLIB => ($word64 ? "/usr/lib64/cracklib_dict" : "/usr +/lib/cracklib_dict");
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re^4: Unable to assign value to constants using ternary operator
by AnomalousMonk (Archbishop) on May 11, 2012 at 15:34 UTC

    I don't see how that works. The code still runs at run-time, and the use statement still runs at compile time. Using  $x instead of  $x == 1 in the ternary eliminates a "Use of uninitialized value $x in numeric eq (==) ..." warning, but that's all.

    >perl -wMstrict -le "my $x; BEGIN { my $m = `uname -m`; print qq{m '$m'} if $m =~ /x86/; $x = 1 if $m =~ /x86/; use constant FOO => ($x ? 'true' : 'false'); } print FOO; print qq{x '$x'}; " m 'x86 ' false x '1'

    Update: This seems to work:

    >perl -wMstrict -le "BEGIN { use constant X => (`uname -m` =~ /x86/) ? 1 : 0; use constant FOO => (X ? 'true' : 'false'); } print FOO; print q{X '}, X, q{'}; " true X '1'

    Update: Oh, wait... I didn't catch the fact that the  use constant statement is outside the BEGIN block! tobyink's code works as advertised (per tobyink's reply which I didn't see until after I had posted this update). Evidently it helps if you test the actual code. Nevermind.

    >perl -wMstrict -le "my $x; BEGIN { my $m = `uname -m`; print qq{m '$m'} if $m =~ /x86/; $x = 1 if $m =~ /x86/; } use constant FOO => ($x ? 'true' : 'false'); print FOO; print qq{x '$x'}; " m 'x86 ' true x '1'

      Your use constant is inside the BEGIN block; my use constant was outside the BEGIN block. That's why mine works and yours does not.

      If you have an inner BEGIN block within an outer BEGIN block, the inner one will execute first, even if it's at the end of the outer block. (And of course use is effectively a BEGIN block.)

      $ perl -e'BEGIN { warn 2; BEGIN {warn 1} }' 1 at -e line 1. 2 at -e line 1.
      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re^4: Unable to assign value to constants using ternary operator
by sathya_myl (Acolyte) on May 11, 2012 at 11:04 UTC

    thanks tobyink, its working fine now.