Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Crazy constant question...

by kennethk (Abbot)
on Dec 15, 2010 at 21:01 UTC ( [id://877377]=note: print w/replies, xml ) Need Help??


in reply to Crazy constant question...

Sticking an evaled use constant in a BEGIN block would seem to meet your requirement, and avoid those nasty typeglobs:
#!/usr/bin/perl use strict; use warnings; my @num_to_name; BEGIN { @num_to_name = qw(FOO BAR); eval "use constant $num_to_name[$_] => $_" for 0 .. $#num_to_name; } print "FOO-->", FOO(), "-->", $num_to_name[FOO];

I've assumed your names are necessarily 1:1 and adjacent integers starting at 0 - this is what your code seems to do. You could do something with hashes instead for more flexibility.

Replies are listed 'Best First'.
Re^2: Crazy constant question...
by ikegami (Patriarch) on Dec 15, 2010 at 21:08 UTC

    Avoiding eval:

    my @num_to_name; BEGIN { @num_to_name = qw(FOO BAR); require constant; constant->import( $num_to_name[$_] => $_ ) for 0 .. $#num_to_name; }

    Avoiding eval and multiple calls to import:

    my @num_to_name; BEGIN { @num_to_name = qw(FOO BAR); require constant; constant->import({ map { $num_to_name[$_] => $_ } 0..$#num_to_name + }); }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-19 02:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found