http://qs321.pair.com?node_id=1142614


in reply to Smoothsort

There shall be no else after return/die/croak. Ever!

sub leonardo{ my $n = shift; if($n == 0 || $n == 1){ return 1; } else{ return leonardo($n-2)+leonardo($n-1)+1; } }

SHould be rewritten to either

sub leonardo { my $n = shift; $n == 0 || $n == 1 and return 1; return leonardo ($n - 2) + leonardo ($n - 1) + 1; }

or using a ternary

sub leonardo { my $n = shift; $n == 0 || $n == 1 ? 1 : leonardo ($n - 2) + leonardo ($n - 1) + 1 +; }

with your personal preference to whitespace and indentation of course.

The else in an if is there to give alternative code in a control flow where the code after the if/else contruct is executed for both branches. As the if branch ends with a return statement, immediatly exiting the routine, the code after if/else is never executed and only written for the else branch making the code harder to read and maintain.


Enjoy, Have FUN! H.Merijn

Replies are listed 'Best First'.
Re^2: Smoothsort
by QuillMeantTen (Friar) on Sep 21, 2015 at 09:55 UTC

    The ternary is really so much more elegant, thanks :D

Re^2: Smoothsort
by Anonymous Monk on Sep 21, 2015 at 09:54 UTC
    ha
    sub leonardo { return 1 if 0==$n or 1==$n; return leonardo ($n - 2) + leonardo ($n - 1) + 1; }
Re^2: Smoothsort
by Anonymous Monk on Sep 21, 2015 at 13:15 UTC
    sub leonardo { my $n = shift; $n <= 1 || leonardo ($n - 2) + leonardo ($n - 1) + 1 +; }
Re^2: Smoothsort
by Anonymous Monk on Sep 21, 2015 at 09:52 UTC

    There shall be no else after return/die/croak. Ever!

    sure there shall for it is allowed