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

Hi Monks,

Stupid question, but I don't know the answer... :(
Is it a must to use "else" at the end of "if" and "elsif" block?

For example:

if (...){...}
elsif(...){...}
elsif(...){...}

Is it a must to use "else" at the end, or it is optional?
Thanks.

Replies are listed 'Best First'.
Re: elsif stupid question...
by Transient (Hermit) on Apr 28, 2005 at 14:43 UTC
    Try it and see what happens :)

    (no you don't have to have an else)
Re: elsif stupid question...
by Joost (Canon) on Apr 28, 2005 at 14:44 UTC
      Thanks, It was in a moment of blackout :)
Re: elsif stupid question...
by cog (Parson) on Apr 28, 2005 at 14:44 UTC
    It is optional, of course. Suppose you want to do something if the input is "1", something other if it is "2", and nothing on any other case:

    if ($input == 1) { # do something } elsif ($input == 2) { # do something other }
Re: elsif stupid question...
by blazar (Canon) on Apr 28, 2005 at 14:48 UTC
    As a side note, if you have a long chain of elsif()'s then chances are that you may choose a "better logic" in the first place. Of course this is just a random observation and may well not be your actual case.

      Yeah, presuming an OOP context lots of branches may indicate you should use the "Replace Conditional with Polymorphism" refactoring. Push the different conditional behaviors down into a method in child classes and just call that method.

      But again, that presumes a set of circumstances which may not apply in this case.

        Yeah, presuming an OOP context lots of branches may indicate you should use the "Replace Conditional with Polymorphism" refactoring.
        Indeed, but not only limited to this case. Of course newbies coming from other languages happen to abuse them where e.g. a hash would have been enough, not to say the best thing! But then again it's not something one can know in advance, from a generic point of view. I only did that remark in the hope that it may have been useful to the OP or to anyone else who will subsequently read the thread.
      Optionally, the nested ternary is good for long chains of if/elsif/else

      #! /usr/bin/perl -w use strict; (my $foo = shift) ||= 0; ($foo == 1) ? print "It's one\n" : ($foo == 2) ? print "It's two\n" : ($foo == 3) ? print "It's three\n" : print "It's nothing meaningful!\n";
        Personally I try to avoid using?: for its side effects, when not golfing - that is! Re the example you gave, a hash or an array would have provided a much neater solution.