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 solution

my %small_hash; @small_hash{@interesting_keys} = @$config{@interesting_keys}; return \%small_hash;

is not acceptable, because keys of interest with false or undefined values are retained, and I want them not to exist.

I have written the following pedestrian solution:

# $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; }

which (barring typos - I haven't tested it yet) does what I want done. But it's horribly repetitive.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.