Home > Software design >  Perl simple way to do multiple decision such as grade scores (except if-elif)?
Perl simple way to do multiple decision such as grade scores (except if-elif)?

Time:08-22

Try to seek Perl experts feedback on approaching this simple scores grading. What I came up is to use conditional opeartor to mimic multiway branch, but wonder if there's more simple/straight syntax to express to enhance the readability (and future maintainability).

Coming from Python/C, and pick up this new language, so I try to explore new syntax. if this sounds too naïve.


my $grade = 
   ($score < 60)  ? "F" :
   ($score < 68)  ? "C" :
   ($score < 75)  ? "B" :
   ($score < 90)  ? "B " :
   ($score < 95)  ? "A" :
   ($score <= 100) ? "A " :
   "No Grade";            # catch-all default
  

CodePudding user response:

You'd either need an hash array of 101 entries, or one with 21 and special cases. The optimization of using a hash array in this fashion would be premature without cause.


One would often use a hash or array as a dispatch table in similar situations, but it doesn't work here since you'd have to include all possible values.

Well, maybe not all possible value. For example, we could truncate the numbers to remove decimal points. And if all the value were divisible by 5, we divide by 5 to obtain a manageable 21 values. Then a dispatch table could be used. (Though an array would work better than a hash.)

That 68 means we can't do that. Either 65, 66 and 67, or 68 and 69 would need to be special-cased. The 100 is also a special value since you apparently want to tolerate invalid inputs. And that suggests a bad design unless performance is crucial.


Let's say the optimization was warranted.

You could setup the following tables:

my @grades_lkup;
$grades_lkup[ $_ ] = "F"  for  0 ..  59;
$grades_lkup[ $_ ] = "C"  for 60 ..  67;
$grades_lkup[ $_ ] = "B"  for 68 ..  74;
$grades_lkup[ $_ ] = "B " for 75 ..  89;
$grades_lkup[ $_ ] = "A"  for 90 ..  94;
$grades_lkup[ $_ ] = "A " for 95 .. 100;

Then all you'd need is

my $grade = $grades_lkup[ $score ] // "No Grade";
  •  Tags:  
  • perl
  • Related