Enums in Perl

Our enum type ServerState has an underlying int type.

use strict;
use warnings;
use feature 'say';

# Define the enum-like structure using constants
use constant {
    STATE_IDLE      => 0,
    STATE_CONNECTED => 1,
    STATE_ERROR     => 2,
    STATE_RETRYING  => 3,
};

# A hash to map states to human-readable strings
my %state_name = (
    STATE_IDLE()      => 'idle',
    STATE_CONNECTED() => 'connected',
    STATE_ERROR()     => 'error',
    STATE_RETRYING()  => 'retrying',
);

# Subroutine to transition server states
sub transition {
    my $state = shift;
    if ($state == STATE_IDLE) {
        return STATE_CONNECTED;
    } elsif ($state == STATE_CONNECTED || $state == STATE_RETRYING) {
        return STATE_IDLE;
    } elsif ($state == STATE_ERROR) {
        return STATE_ERROR;
    } else {
        die "unknown state: $state";
    }
}

# Print the state names using the hash
sub state_to_string {
    my $state = shift;
    return $state_name{$state};
}

# Main function to demonstrate state transitions
sub main {
    my $ns = transition(STATE_IDLE);
    say state_to_string($ns);

    my $ns2 = transition($ns);
    say state_to_string($ns2);
}

# Call the main function
main();

To run the Perl script, save it to a file, for example, enums.pl, and execute it using the Perl interpreter.

$ perl enums.pl
connected
idle

In this example, we defined the enum-like structure using constants and leveraged a hash to map state values to their respective names in a human-readable format. We also implemented a transition subroutine to handle state transitions for a server, showcasing how you can work with enums in Perl. The main function demonstrates the state transitions by printing out the states using the state_to_string subroutine.