http://qs1969.pair.com?node_id=730734

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

One can apply a conditional to a bare statement. Is there a way to apply it a block of statements using the same style? For example:
$true = 1; print "eenie\n" if $true; print "meenie\n" if $true; {print "miney\n"; print "moh\n";} if $true;

Replies are listed 'Best First'.
Re: Conditional for statement block (not just bare statement)
by jeffa (Bishop) on Dec 16, 2008 at 20:44 UTC

    Yes. But why? What does that (and the fun provided by ikegami) buy you? What value does it add to your code to forsake a simple, traditional if block?

    if ($true) { print "eenie\n"; }
    versus
    do { print "meenie\n"; } if ($true);
    I can understand prefering a do-while over a while loop, but this is mostly pointless. I never write single line if statement anymore because i find they get in the way of debugging and growth. But I will use a do-while from time to time because it is necessary.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    

      No disagreement with most of what you've written, but 'while' and 'do/while' have different purposes. I suppose that it can be considered a matter of preference, but IMO, forcing one to serve the purpose of the other is a bit square-block-into-round-hole-ish. :)

      do { print "Please enter $THING_TO_VALIDATE"; chomp($input = <STDIN>); } while THING_IS_NOT_VALID();

      --
      "Language shapes the way we think, and determines what we can think about."
      -- B. L. Whorf
Re: Conditional for statement block (not just bare statement)
by ikegami (Patriarch) on Dec 16, 2008 at 20:32 UTC
    do{print "miney\n"; print "moh\n";} if $cond;

    Update: For fun:

    map{print "miney\n"; print "moh\n";} 1 if $cond;
    grep{print "miney\n"; print "moh\n";} 1 if $cond;
    sub{print "miney\n"; print "moh\n";}->() if $cond;
    sub doif(&$) { $_[0]->() if $_[1] } doif{print "miney\n"; print "moh\n";} $cond;
    print("miney\n"),print("moh\n") if $cond;
    (print "miney\n"),(print "moh\n") if $cond;
Re: Conditional for statement block (not just bare statement)
by sundialsvc4 (Abbot) on Dec 17, 2008 at 01:17 UTC

    I strongly agree...

    Think future modifications, made in a hurry (of course) by people who don't fully understand your code (of course), or by you when either of the above apply (of course).

    You need to write your code so that it is easy to modify in such a way that you are unlikely to “write it wrongly.” Extra braces, extra punctuation, easy-and-obvious indentation style ... all those “unnecessary (sic...) uses of white-space” ... really pay off during the many-years-long practical lifespan of an application.

    “Don't try to be cute or clever. You'll regret it.”