Update
I like both the replies that just came in. Thank you both! I am given a configuration hash reference and three keys of interest. I have to return a hash reference that contains at most the three keys of interest, but omits them if their configured value is false, undefined, or nonexistent. So the simple hash-slicing solutionis not acceptable, because keys of interest with false or undefined values are retained, and I want them not to exist.my %small_hash; @small_hash{@interesting_keys} = @$config{@interesting_keys}; return \%small_hash;
I have written the following pedestrian solution:
which (barring typos - I haven't tested it yet) does what I want done. But it's horribly repetitive.# $config is given sub get_file_watcher_ref { my %setting_for; my ( $watch_interval, $watch_file_min_size, $term_run_time, ); if ( $watch_interval = $config->{watch_interval} ) { $setting_for{watch_interval} = $watch_interval; } if ( $watch_file_min_size = $config->{watch_file_min_size} ) { $setting_for{watch_file_min_size} = $watch_file_min_size; } if ( $term_run_time = $config->{term_run_time} ) { $setting_for{term_run_time} = $term_run_time; } return \%setting_for; }
Does anyone know an elegant way to write this?
Update
I must have momentarily forgotten how to loop. Here's what I meant to do.sub get_file_watcher_ref { my %setting_for; my @interesting_keys = qw( watch_interval watch_file_min_size term_run_time ); for (@interesting_keys) { if ($config->{$_}) $setting_for{$_} = $config->{$_}; } return \%setting_for; }
The loop still feels kind of clumsy. Any suggestions for improvement?
In reply to [Answered!] Taking a subset of a hash by Narveson
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |