in reply to Conditional within Hash definition

ok so I seem to have managed to make it work using x ==y ? 'true' : 'false' format - is it not possible using if and else?

Replies are listed 'Best First'.
Re^2: Conditional within Hash definition
by tobyink (Canon) on Jan 28, 2014 at 22:53 UTC

    if(...){...}else{...} is considered a statement rather than an expression. Any expression can be used as a statement, but many statements cannot be used as an expression.

    In a list (which is what a hash is initialized with), the list items are expected to be given as expressions, not statements.

    The ternary operator is an expression, which is why that works.

    A do{...} block allows you to provide a block of statements and wrap it up into an expression:

    my %weather = ( precipitation => do { if ($rain == 0) { "dry"; } else { "wet"; } }, );
    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

      A couple other examples along these lines:

      my ($x, $y, $z) = ( ... ); ... my %weather = ( 'precip' => get_precip_function($x, $y, $z), 'wind_speed' => sub { ... }->($z, $y, $x), ..., );
Re^2: Conditional within Hash definition
by Laurent_R (Canon) on Jan 28, 2014 at 19:49 UTC
    You could with a do{} block, but the ternary operator is there and fancier.