in reply to Ternary Operator with Subroutine

This would work:

( my $test ) ? print 'c' : sub { print 'a'; print 'b' }->();

But this is probably what you want:

( my $test ) ? print 'c' : do{ print 'a'; print 'b' };

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.

Replies are listed 'Best First'.
Re^2: Ternary Operator with Subroutine
by egga (Monk) on Aug 12, 2011 at 08:37 UTC

    There must be something I didnt understand yet, so I excuse my question, dear Monks. But why would anyone would like to do that? Is there any possibility, that

    my $test
    may fail?

    It seems to me like writing

    if (1) { print "some"; } else { print "thing"; }
    (And in that case, I could imagine some kind of debug-switch or so).

    Please enlighten me.

      Is there any possibility, that my $test may fail?

      Actually, it will always "fail". That is, an uninitialised variable is always undef, and therefore false.

      It also doesn't make much sense to do print 'a'; print 'b'; instead of print 'a', 'b'; or print 'ab';.

      I think it is fair to assume that the code supplied it greatly simplified example and that ( my $test ) is just a placeholder for 'some boolean condition' rather than an actual variable declaration.


      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^2: Ternary Operator with Subroutine
by Jim (Curate) on Aug 14, 2011 at 16:24 UTC

    The statement…

    ( my $test ) ? print 'c' : do{ print 'a'; print 'b' };

    …is much better written…

    print 'a'; print 'b';

      No shit Sherlock!


      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.