Popcorn Dave has asked for the wisdom of the Perl Monks concerning the following question:
I'm doing a conversion of some pascal code of a friend's to Perl to convince him to learn Perl. And after seeing his 8 pages of code I was sorely convinced I could do it in no more than 2 in Perl and still make it non-obsfu. :)
Given the following code in pascal:
function roll(point : integer) : real; begin case point of 2,12: roll := 1/36; 3,11: roll := 2/36; 4,10: roll := 3/36; 5,9: roll := 4/36; 6,8: roll := 5/36; 7: roll := 6/36; else writeln('invalid roll'); roll := 0; end; { case } end; { rolls }
This is what I've converted it to in Perl:
sub roll{ my $i = shift; my %roll=( 2=>1, 3=>2,4=>3, 5=>4, 6=>5, 7=>6, 8=>5, 9=>4, 10=>3, 11=>2, 12=>1); $i = $roll{$i}/36; return $i; }
What I'm curious about is this: Is there a way to do this cleaner or more efficiently? At first I thought tr was the way to go until I realized it was only going to work for 2-9, and once you hit 10-12 you were stuck.
I also thought about the array approach using just the indicies 2-12 but the hash just lays it out so well.
Any ideas would be greatly appreciated!
Some people fall from grace. I prefer a running start...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Converting pascal code to perl
by YuckFoo (Abbot) on Aug 15, 2002 at 04:01 UTC | |
by Popcorn Dave (Abbot) on Aug 15, 2002 at 04:34 UTC | |
|
Re: Converting pascal code to perl
by spurperl (Priest) on Aug 15, 2002 at 06:26 UTC | |
by Popcorn Dave (Abbot) on Aug 15, 2002 at 16:18 UTC | |
|
Re: Converting pascal code to perl
by BrowserUk (Patriarch) on Aug 15, 2002 at 04:45 UTC | |
|
Re: Converting pascal code to perl
by Anonymous Monk on Aug 15, 2002 at 03:47 UTC | |
|
Re: Converting pascal code to perl
by Abigail-II (Bishop) on Aug 15, 2002 at 09:42 UTC | |
by mp (Deacon) on Aug 15, 2002 at 16:39 UTC | |
|
Re: Converting pascal code to perl
by Necos (Friar) on Aug 15, 2002 at 09:39 UTC | |
|
Re: Converting pascal code to perl
by greenFox (Vicar) on Aug 16, 2002 at 03:33 UTC |