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.
In reply to General style advice requested by iangibson
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |