I wanted to share with you guys a function I had created to see how I could optimize it, or if there was a better way to do this.
sub flatten{
my($ref,$delim,$item_delim,$array,$str) = @_;
die("Required Hash Reference") unless isHash($ref);
$delim = $delim ? $delim :'_';
#dump into array hash vals #simplified
if(!$item_delim){
@{$array} = %{$ref};
}else{
my($keys,$values);
$keys = getKeys($ref);
$values = getValues($ref);
#item strings
if($#$keys > 0 && $#$values > 0){
#fix for issue where value[n] is empty
@{$array}= map{ (defined $$values[ $_ ]) ? $$keys[ $_ ].$item_delim.$$values[ $_ ] : $$keys[ $_ ].$item_delim } 0 .. int($#$keys);
}else{
log "No Values to flatten";
return '';
}
}
$str = join($delim,@{$array});
return $str;
}
Are there any optimization points I should be aware of here?
Basically I want to go from
$HASH => {
key1 => 'val1',
key2 => 'val2',
key3 => 'val3',
}
to $STRING= key1=val1&key2=val2 ...
UPDATED
a solution without Modules is preferred I really just want to know how to effectively flatten a hash!.
Note that some of the functions here are simply wrapper functions that do what they say. isHash getKeys… pay no attention to those!
Without modules:
result: