Fellow monks,

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.