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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.