Today's mission, if you choose to accept it, is to help me deal with some very repetitive code. I have a script that works beautifully, but has a problem. It repeats this code about 11 times:
our %<name>Cmd; do 'db/<name>Cmd.pm'; $ApidOffset = $Application{<name>}{AppApidOffset}; foreach $cmd (keys %<name>Cmd) { if (int($fssbCmd{$cmd}{fixed_pattern}) <= 15) { $opcode = sprintf("0%x",$<name>Cmd{$cmd}{fixed_pattern}); } else { $opcode = sprintf("%x",$<name>Cmd{$cmd}{fixed_pattern}); } $apid = sprintf("%x",$ApidBase+$ApidOffset); $cmdData{$cmd} = {opcode => "0x$opcode", apid => "0x$apid"}; };
Wherever you see <name>, that indicates where the code differs each time. I have a bunch of files with the naming convention <name>Cmd.pm, and each file contains a hash called <name>Cmd. In each case, I need to get at the array in the file and do the exact same thing to it.
So I have this code repeating right now, once for each file. I know there has to be a better way, but all I'm coming up with so far is naming a variable with a variable, which seems generally a bad idea, and I'm not too sure it would work anyway.
So here I am, dear Monks - hoping someone knows a better way. A way that will work without repeating the same code 11 times. A way that won't induce heavy drinking and swearing in anyone working with this code after me.
Also, here's an example of the type of data that is being sucked in from the <name>Cmd.pm files:
%<name>Cmd = ( 'command_1' => { _discussion => ' some text about command_1', description => ' shorter text about command_1', safety_level => 'SAFE', fixed_pattern => '143', constraints => undef, build_types => [ 'FLIGHT' ], cmd_id => 250033, target => 'command_target', Command_maps => [] }, 'command_2' => { _discussion => ' some text about command_2', description => ' shorter text about command_2', safety_level => 'SAFE', fixed_pattern => '144', constraints => undef, build_types => [ 'FLIGHT' ], cmd_id => 250014, target => 'command_target', Command_maps => [] } );
As always, THANK YOU!
In reply to Repeating Code - there has GOT to be a better way! by jedikaiti
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |