Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: Repeating Code - there has GOT to be a better way!

by jethro (Monsignor)
on Mar 31, 2010 at 17:33 UTC ( #832100=note: print w/ replies, xml ) Need Help??

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}'; $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"

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2016-08-28 09:57 GMT
Find Nodes?
    Voting Booth?
    The best thing I ever won in a lottery was:

    Results (392 votes). Check out past polls.