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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|