Can't do it with built-ins, but it's easy to create a function that can do it.

#!perl use strict; use warnings; BEGIN { package Hash::Adjust; use Exporter::Shiny 'ha'; sub _generate_ha { my ( $me, $name, undef, $opt ) = ( shift, @_ ); my ( $aref, $bref ) = do { no strict 'refs'; my $caller = $opt->{into}; ( \${"$caller\::a"}, \${"$caller\::b"} ); }; return sub (&\%) { my ( $code, $hashref ) = ( @_ ); @_ = (); my %tmp; while ( ( $$aref, $$bref ) = each %$hashref ) { &$code; $tmp{$$aref} = $$bref if defined $$aref; } %$hashref = %tmp; }; } }; use Hash::Adjust 'ha'; use Data::Dumper; my %hash = ( FOO => 42, BAR => 666 ); ha { $a =~ s/O/o/g; ++$b; } %hash; print Dumper \%hash;

The ha function is called like ha { CODE } %hash and modifies the keys and values of the hash. The code gets the key in $a and the value in $b; the same special global variables used by sort. If the code block sets $a = undef then that key-value pair will be removed from the hash.


In reply to Re: can I change hash keys or values directly by tobyink
in thread can I change hash keys or values directly by misterperl

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.