Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Does perl offer an auto incremental assigning of constants, like Swift?

by Perlbotics (Bishop)
on Apr 18, 2022 at 19:07 UTC ( #11143057=note: print w/replies, xml ) Need Help??


in reply to Does perl offer an auto incremental assigning of constants, like Swift?

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11143057]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2023-03-26 10:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which type of climate do you prefer to live in?






    Results (63 votes). Check out past polls.

    Notices?