http://www.perlmonks.org?node_id=832100


in reply to Repeating Code - there has GOT to be a better way!

Is the code in the pm files fixed? Or generated by some other script? Or handwritten? If it is fixed I don't see anything better than to use symbolic references (or use eval which is not that different from using a symbolic ref in this case). But you could at least confine it to a small part of your code and put warning signs around it (this is totally untested code and sure to contain bugs) :

my $Cmdref; #---------- # Using symbolic references to get code files into name space no strict refs; eval "our %${name}Cmd; do 'db/${name}Cmd.pm'; $Cmdref= \%${name}Cmd;"; use strict refs; #----------- ... foreach $cmd (keys %$Cmdref) { ... $opcode = sprintf("0%x",$Cmdref->{$cmd}{fixed_pattern});

But if the data in those files could look different you have a lot more options. You could change it to look like a real module and use the core-module Exporter to get the hashes into your namespace. Or simply have some code that adds a reference to each hash into a global array:

my %ThingyCmd= ... push @main::allCmd,\%ThingyCmd;

Or you could create files that conform to Storable, JSON or to the Data::Dumper file format and use the corresponding CPAN modules to read them in. I believe Data::Dumper calls that "thaw"