bartender1382 has asked for the wisdom of the Perl Monks concerning the following question:

Swift has a wonderful feature which auto enumerates values like this:

enum ButtType : Int { case inv = 0 case tut case sup case main case stop case reg case log case set case back case new case old case up case file }</p>

In perl I am doing this for errors

use constant { SSSUCCESS => 0, SSD001 => 1, SSD002 => 2, SSFAILEDRAWDB => 3, ... };</p>

Would be nice if there was something available, like in Swift. Otherwise every time I come up with a new error, to keep them related ones together I have to insert, renumber, etc.

Replies are listed 'Best First'.
Re: Does perl offer an auto incremental assigning of constants, like Swift?
by choroba (Cardinal) on Apr 17, 2022 at 18:15 UTC
    enum can do that any many more (e.g. bitmask constants).

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      Thanks, should have thought first to check for a module
Re: Does perl offer an auto incremental assigning of constants, like Swift?
by tybalt89 (Monsignor) on Apr 17, 2022 at 19:06 UTC

    If you keep the numbers aligned in a column, vim is great at incrementing and decrementing columns of numbers.

Re: Does perl offer an auto incremental assigning of constants, like Swift?
by Perlbotics (Archbishop) on Apr 18, 2022 at 19:07 UTC

    Just a try...

    use strict; use warnings; use Carp; use Scalar::Util qw(looks_like_number); sub make_const { my ( $package, $start_i, $inc, @names ) = @_; croak "Expecting at least 3 parameters!" if @_ < 3; croak "'$package' - invalid package name!" if $package !~ /^(\w+) +(::\w+)*$/; croak "start_i = '$start_i' is not a number!" unless looks_like_numb +er( $start_i ); croak "inc = '$inc' is not a number!" unless looks_like_numb +er( $inc ); carp "inc=0 probably makes no sense" unless $inc; foreach ( @names ) { eval "sub $package\::$_ { return $start_i }"; $start_i += $inc; } } BEGIN { make_const( 'main', 0, 1, qw(inv tut sup main stop reg log set bac +k new old up file) ); #-- better avoid collisions by not using 'main' / uppercase const +ants are common make_const( 'Enum', 10, -2, qw(A B C D E) ); # croaks: make_const( 'X {1}; system("cat /etc/passwd"); sub Enum', + 10, -2, qw(A B C D E) ); } print "1st list of enums: ", join(', ', inv, tut, up, file ), + "\n"; print "2nd list of enums: ", join(', ', Enum::A, Enum::B, Enum::E ), + "\n";

    Result:

    1st list of enums: 0, 1, 11, 12 2nd list of enums: 10, 8, 2