Currently I have a sub like this (scrubbed for public display)
I'm going to be getting a few more types and it seems silly to just keep building out that if statement (in the real code I'm setting a few hundred value plus doing a lot of calculations)
I was thinking something like this would be better but wanted to see if others had a better idea
or even
I would have to of course work out a few issues but I definitely don't want to be maintaining 5+ if statements that are almost identical and are hundreds of lines long every time I need a new values. Mainly I just wanted to see what kind of suggestions come up that I wouldn't have though about.
Hopefully the explanation is ok!
Thanks!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
Code:
sub decode_data {
my $type = shift @_;
my $date = shift @_;
my (%return_data, $csv);
if ($type =~ /TYPE1/i) {
$csv = Text::CSV_XS->new({binary => 1, allow_loose_quotes => 1, allow_loose_escapes => 1, verbatim => 1, escape_char => '`'});
}
elsif ($type =~ /TYPE2/i) {
$csv = Text::CSV_XS->new({binary => 1, allow_loose_quotes => 1, allow_loose_escapes => 1, verbatim => 1, escape_char => '/', quote_char => undef});
}
if ($csv->parse($line)) {
my @col = $csv->fields();
if ($type =~ /TYPE1/i){
$return_data{val1} = $col[1];
$return_data{val2} = $col[2];
$return_data{val3} = $col[3];
}
#Yes this is here but not defined exactly above because the first regex catches it.
#Data is in the same place but sometime treated differently
elsif ($type =~ /TYPE21/i){
$return_data{val1} = $col[5];
$return_data{val2} = uc $col[6];
$return_data{val3} = lc $col[7];
}
elsif ($type =~ /TYPE2/i){
$return_data{val1} = $col[5];
$return_data{val2} = $col[6];
$return_data{val3} = $col[7];
}
}
else {
$return_data{status} = 'fail';
}
return(%return_data);
}
I was thinking something like this would be better but wanted to see if others had a better idea
Code:
%config = ( 'TYPE1' => {
'val1' = 1,
'val2' = 2,
'val3' = 3,
},
'TYPE2' => {
'val1' = 5,
'val2' = 6,
'val3' = 7,
},
)
$return_data{val1} = $col[$config{$type}{val1}];
$return_data{val2} = $col[$config{$type}{val2}];
$return_data{val3} = $col[$config{$type}{val3}];
Code:
for my $key (keys %{$config{$type}}){
$return_data{$key} = $col[$config{$type}{$key}];
}
Hopefully the explanation is ok!
Thanks!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;