Narveson has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Taking a subset of a hash
by choroba (Cardinal) on Oct 30, 2010 at 13:17 UTC | |
|
Re: Taking a subset of a hash
by BrowserUk (Patriarch) on Oct 30, 2010 at 13:22 UTC | |
by Narveson (Chaplain) on Oct 30, 2010 at 13:28 UTC | |
by BrowserUk (Patriarch) on Oct 30, 2010 at 13:59 UTC | |
|
Re: Taking a subset of a hash
by james2vegas (Chaplain) on Oct 30, 2010 at 13:18 UTC | |
|
Re: Taking a subset of a hash
by roboticus (Chancellor) on Oct 30, 2010 at 13:37 UTC | |
|
Re: [Answered!] Taking a subset of a hash
by ig (Vicar) on Oct 30, 2010 at 21:48 UTC |