Logo

Programming-Idioms

  • Pascal
  • Perl

Idiom #269 Enum to String

Given the enumerated type t with 3 possible values: bike, car, horse.
Set the enum value e to one of the allowed values of t.
Set the string s to hold the string representation of e (so, not the ordinal value).
Print s.

use enum qw(bike car horse);

my $e = horse;
print $e;

Part 1: perl doesn't have native support for enums, but the enum module can satisfy the first half of this -- setting a variable using an enum value. See part 2 for the rest.
use enum     qw(bike car horse);
my @enum_T = qw(bike car horse);

my $e = horse;
my $s = $enum_T[$e];
print $s;

Part 2: the enum module doesn't provide means to map an emun value back to it's name. The most reliable way to do this is simply define a corresponding list of the enum values. (But this doesn't work if you change the index values in the enum declaration.)
  e := horse;
  writestr(s, e);
  writeln(e);

Prints: horse
with Ada.Text_IO;
declare
   type T is (Bike, Car, Horse);
   E : constant T      := Horse;
   S : constant String := T'Image (E);
begin
   Ada.Text_IO.Put_Line (S);
end;

New implementation...
< >
Bart