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

Alright, here's what I have:
$ref_to_all_lines_in_file # contains all lines in file minus those i +n %hash or @array @array; # contains some lines from the file %hash; # contains array refs $hash_count; # totals all arrays referenced in %hash $array_count; # scalar(@array); $ref if($hash_count) { $ref = \%hash; } elsif($array_count) { $ref = \@array; } else { $ref = $ref_to_all_lines_in_file; }
so that works and all.. just thought it'd be neater to do a nested ternary operator like:
$ref = $hash_count ? \%hash : { $array_count ? \@array : $ref_to_all_l +ines_in_file };
however, this doesn't seem to be working.. should it be possible to do this? or I am just high off the paint fumes meandering in from the construction on the other side of the wall? :)

-brad..

Replies are listed 'Best First'.
(jcwren) Re: Nested Ternary Operators
by jcwren (Prior) on Nov 20, 2000 at 23:28 UTC
    It probably doesn't work because you're using braces, instead of parenthesis.

    Which means that you're setting $ref to an anonymous hash, if $hash_count is zero.

    Consider this code, and it's output:
    #!/usr/local/bin/perl -w use strict; use Data::Dumper; { my $a = 0; my $b = 1; my $c = 2; # # $a is 0, so the second term will be evaluated # $b is meaningless, and just used as a place holder # $c is 2, so 3 should be the answer. # my $right = $a ? $b : ($c ? 3 : 4); my $wrong = $a ? $b : {$c ? 3 : 4}; print "Right=", $right, "\n"; print "Wrong=", $wrong, "\n"; print Dumper ([\$right]); print Dumper ([\$wrong]); }

    Odd number of elements in hash assignment at t line 17. Right=3 Wrong=HASH(0x80e6154) $VAR1 = [ \3 ]; $VAR1 = [ \{ 3 => undef } ];
    --Chris

    e-mail jcwren
Re: Nested Ternary Operators
by Dominus (Parson) on Nov 21, 2000 at 00:26 UTC
    The ternary operator was designed (by Thompson and Ritchie, the inventors of C) to make this sort of thing simple.

    Just use:

    $ref = $hash_count ? \%hash : $array_count ? \@array : $ref_to_all_lines_in_file;
    Note that no parentheses of any sort are necessary.

Re: Nested Ternary Operators
by KM (Priest) on Nov 20, 2000 at 23:22 UTC
    What do you mean "isn't working"? Do you get an error? The following works fine for me (5.6):

    my $foo = 0; my $baz = 0; my $bar = $foo ? 1 : ($baz ? 4 : 2); print $bar;

    Cheers,
    KM