iangibson has asked for the wisdom of the Perl Monks concerning the following question:
I am a newcomer to Perl (and to programming in general; I just finished the Llama book) and someone recommended that I work through the problems on the http://www.streamtech.nl/site/problem+set website by way of practice. This is my attempt at the first problem. It produces the correct output, so I'd just like to know if there's any style issues or other bad practices in my code that I should know about:
#!/usr/bin/perl use warnings; use strict; use 5.010; # The 3n + 1 problem (http://www.streamtech.nl/problemset/100.html) my ( $first, $second, $cycle_length ); my $max_cycle_length = 0; say "Input:"; chomp( my @pairs = <> ); say "Output:"; foreach my $pair (@pairs) { ( $first, $second ) = split( / /, $pair ); foreach my $num ( $first .. $second ) { $cycle_length = totalizer($num); if ( $cycle_length > $max_cycle_length ) { $max_cycle_length = $cycle_length; } } say "$first $second $max_cycle_length"; } sub totalizer { my $number = shift; $cycle_length = 0; { ++$cycle_length; last if ( $number == 1 ); if ( $number % 2 != 0 ) { $number = ( $number * 3 + 1 ); } else { $number = $number / 2; } redo; } return $cycle_length; }
The Wisdom of the Monks will be most welcome.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: General style advice requested
by toolic (Bishop) on Oct 22, 2010 at 02:32 UTC | |
Re: General style advice requested
by JavaFan (Canon) on Oct 22, 2010 at 02:34 UTC | |
Re: General style advice requested
by ikegami (Patriarch) on Oct 22, 2010 at 02:45 UTC | |
Re: General style advice requested
by morgon (Priest) on Oct 22, 2010 at 03:14 UTC | |
Re: General style advice requested
by snape (Pilgrim) on Oct 22, 2010 at 02:37 UTC | |
Re: General style advice requested
by AnomalousMonk (Archbishop) on Oct 23, 2010 at 13:14 UTC | |
by iangibson (Scribe) on Oct 23, 2010 at 17:08 UTC | |
Re: General style advice requested
by iangibson (Scribe) on Oct 23, 2010 at 17:03 UTC | |
by GrandFather (Saint) on Oct 23, 2010 at 21:51 UTC | |
by choroba (Cardinal) on Oct 29, 2010 at 14:47 UTC |