I have a module with a set of functions implemented as a dispatch hash with a helper function thus:
my $functions = {
'f1' => sub {
my %args = @_;
## process data ...
return $answer;
},
[etc.]
};
sub do_function {
my $fn = shift;
return $functions->{$fn}(@_);
}
This is used by some scripts that process tab-delimited data; the column being examined is converted by the appropriate subroutine. When processing a value in a column, I pass a hash of data to the sub, and it generates a scalar, the new value for the column.
Currently the subs are called thus:
my $new_value = do_function( 'f1', data => $data, errs => $errs );
and the variables in the arguments are all declared as ‘my’ – my $data, my $errs, etc.. Is it possible to update other values in the arguments that are passed into the subs without having to return them? i.e. instead of having to do this:
... in $functions->{f1}:
my %args = @_;
## process data ...
## alter $args{errs}
$args{errs}->{type_one_error}++;
## ...
return { answer => $answer, errs => $args{errs} };
...
## call the function, get the response, update the errs
my $return_data = do_function( 'f1', data => $data, errs => $errs );
my $new_value = $return_data->{answer};
$errs = $return_data->{errs}; ## this has been altered by sub 'f1'
I could do this:
my $new_value = do_function( 'f1', data => $data, errs => $errs );
## no need to update $errs, it has been magically updated already!
You can pass reference to value and update it inside of subroutine.
For example:
And as far as I can see from your code snippets,
$errsis already reference to hash.So, actually, all you have to do – just comment out line
$errs = $return_data->{errs};and tryIf I get your code right,
$errsgets updated. And then you should just change your return value to$answerand do: