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...
In reply to Converting pascal code to perl by Popcorn Dave
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |