lwicks has asked for the wisdom of the Perl Monks concerning the following question:
As part of my "get better with Perl" campaign, I have started running through cyber-dojo.com exercises when time permits. Tonight I took a run at the 100 doors exercise.
Doing it was good and educational "deliberate practise" for me. But I know form the office that code review is a great way to learn. So I turn to you oh PerlMonks community, please if you have some time and enthusiasm, please review my code (below) and tell me how you would improve it.
I am hoping to create code that is not "clever" rather "maintainable". So please review it in that light if you could (i.e. I'm not wanting to learn obfuscation).
Thanks!
doors.t
doors.perl:use strict; use warnings 'all'; use Test::More qw( no_plan ); require "doors.perl"; # Initialise array of doors. my @doors = init_doors(); is($doors[1], 'Closed', 'Door one should be closed'); is($doors[100], 'Closed', 'Door 100 should be closed'); toggle_door(\$doors[1]); is($doors[1], 'Open', 'Door one should be closed'); toggle_door(\$doors[1]); is($doors[1], 'Closed', 'Door one should be open'); my @answer = loop_through_doors(); # Doors open are: 1, 4, 9, 16, 25, 36, 49, 64, 81, and 100 is($answer[1], 'Open'); is($answer[4], 'Open'); is($answer[9], 'Open'); is($answer[16], 'Open'); is($answer[25], 'Open'); is($answer[36], 'Open'); is($answer[49], 'Open'); is($answer[64], 'Open'); is($answer[81], 'Open'); is($answer[100], 'Open'); # Check some of the other doors are closed. is($answer[2], 'Closed'); is($answer[3], 'Closed'); is($answer[50], 'Closed'); is($answer[99], 'Closed');
You may also be able to look at it on Cyber-Dojo via the following link, I am not sure how long it remains live for however: Cyber-Dojo Linkuse strict; use warnings; sub init_doors { my @doors; for my $i (1 .. 100) { $doors[$i] = 'Closed'; } return(@doors); } sub toggle_door { my $door_ref = shift; if( $$door_ref eq 'Closed' ) { $$door_ref = 'Open'; } else { $$door_ref = 'Closed'; } return $$door_ref; } sub loop_through_doors { my @doors = init_doors(); for my $pass (1 .. 100) { for my $visit (1 .. 100) { if (($visit % $pass) == 0) { toggle_door(\$doors[$visit]); } } } return(@doors); } 1;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Please review my code: 100 Doors.
by choroba (Cardinal) on Jul 02, 2013 at 20:28 UTC | |
|
Re: Please review my code: 100 Doors.
by AnomalousMonk (Archbishop) on Jul 02, 2013 at 23:17 UTC | |
by lwicks (Friar) on Jul 03, 2013 at 08:01 UTC | |
|
Re: Please review my code: 100 Doors.
by Loops (Curate) on Jul 02, 2013 at 20:38 UTC |