in reply to Unable to assign value to constants using ternary operator

use is evaluated at compile time, but the value of $word64 is not known at compile time. You could replace $word64 with another constant to fix that.

Replies are listed 'Best First'.
Re^2: Unable to assign value to constants using ternary operator
by sathya_myl (Acolyte) on May 11, 2012 at 10:22 UTC

    thanks for the reply moritz but i'm assigning the value of $word64 based on a condition.Here is the code:

    my $hw = `uname -i`; my $word64 = 1 if ( $hw =~/x86_64|ia32e/);

    Now how can i use constant for this one?

      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'

        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'

        thanks tobyink, its working fine now.