While optimizing an application I found the following code snippet, which is deleting comma separated hash value.
Here is what the code is doing:

  • get the comma separated value of '%new_reports' hash based on each '@key_to_search' array elements.
  • search for '@element_to_delete' array elements in comma separated value of hash and delete the element if found.
    Also delete '%new_reports' hash key, If no value exist for that particular key.

    Here is the Dumper output before deleting.
    $VAR1 = { '10' => 'Test1,Test2,Test3,Test4,Test5,Test6', '20' => 'Test4' };
    Dumper output after deleting
    $VAR1 = { '10' => 'Test1,Test3,Test5,Test6' };

    Code taken from the original application.
    #!/usr/bin/perl use warnings; use strict; use Data::Dumper; my %new_reports = ( 10 => 'Test1,Test2,Test3,Test4,Test5,Test6', 20 => 'Test4' ); print Dumper(\%new_reports); my @key_to_search = qw(10 20); my @element_to_delete = qw(Test2 Test4); foreach (@key_to_search) { if($new_reports{$_}) { my @sel_reports = split(/,/,$new_reports{$_}); map{ my $element_to_remove = $_; @sel_reports = grep { $_ ne $element_to_remove } @ +sel_reports; }@element_to_delete; if(scalar(@sel_reports) > 0) { $new_reports{$_} = join(",",@sel_reports); } else { delete $new_reports{$_}; } } } print Dumper(\%new_reports);

    Is there any better way to acheive the same?

    --lamp

    In reply to better way delete comma separated hash values? by lamp

    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.