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

hello ! how do I concat a string with a variable from a ternary operation like :
$cl='color:'.$c_diff<=0?$color_good:$color_bad.';';
instead of
$cl = 'color:'; $cl .= $c_diff<=0?$color_good:$color_bad; $cl .= ';';

Replies are listed 'Best First'.
Re: concat string with ternary operator
by choroba (Cardinal) on Jul 02, 2011 at 11:35 UTC
    $cl = 'color:' . ($c_diff <= 0 ? $color_good : $color_bad) . ';'; Mind the precedence of operators.
      thanks, this worked !
Re: concat string with ternary operator
by BrowserUk (Patriarch) on Jul 02, 2011 at 14:03 UTC

    Personally, I find this to be cleaner:

    $cl = sprintf 'color:%s;', $c_diff <= 0 ? $color_good : $color_bad;

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: concat string with ternary operator
by AnomalousMonk (Archbishop) on Jul 02, 2011 at 13:55 UTC

    Surely, this is a question susceptible to just a little bit of experimentation:

    >perl -wMstrict -le "my $which; my $s = 'foo' . $which ? 'bar' : 'baz' . 'boff'; ;; $s = 'foo' . ($which ? 'bar' : 'BAZ') . 'boff'; print qq{'$s'}; ;; $which = 1; $s = 'fee' . ($which ? 'FIE' : 'foe') . 'fum'; print qq{'$s'}; " Use of uninitialized value $which in concatenation (.) or string ... 'fooBAZboff' 'feeFIEfum'