sub toggle_door { my $door_ref = shift; if( $$door_ref eq 'Closed' ) { $$door_ref = 'Open'; } else { $$door_ref = 'Closed'; } return $$door_ref; }

My own preference is to avoid  if ... else ... or  if ... elsif ... else ... vipers' nests if possible — and if you add another state or states (e.g., 'HalfClosed'), you'll have to add one or more  elsif clauses. "But this application will never, ever require another state", you say. Famous last words.

The following is my preferred approach to something like this. Most of the heavy lifting is actually data validation. (The state keyword requires Perl version 5.10+.) The following is tested per your test plan:

sub toggle_door { my ($door_ref) = @_; state $transition = { qw(Open Closed Closed Open) }; $$door_ref // die 'undefined door state'; exists $transition->{$$door_ref} or die qq{unknown door state '$$door_ref'}; return $$door_ref = $transition->{$$door_ref}; }

At some sacrifice of self-documentation,  $_[0] can be used in place of  $$door_ref throughout the  toggle_door() function, in which case the initial
    my ($door_ref) = @_;
statement is not needed, and, important note, the function is called with no reference taken, e.g., toggle_door($doors[$i]);(also tested, but I'm not sure I would actually use this):

sub toggle_door { state $transition = { qw(Open Closed Closed Open) }; $_[0] // die 'undefined door state'; exists $transition->{$_[0]} or die qq{unknown door state '$_[0]'}; return $_[0] = $transition->{$_[0]}; }

In reply to Re: Please review my code: 100 Doors. by AnomalousMonk
in thread Please review my code: 100 Doors. by lwicks

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.