in reply to Mapping array over a hash

You're trying to be too complicated. Instead of taking a hash and removing what shouldn't be there, why don't you just create a new hash by adding what should be there. Something along the lines of:

my %hash2; for (@ary) { $hash2{$_} = $hash1{$_} if exists $hash1{$_}; } undef %hash1;

Replies are listed 'Best First'.
Re: Re: Mapping array over a hash
by agoth (Chaplain) on Jul 20, 2001 at 18:02 UTC
    UPDATED For the reason that the array is coming in from user input (Getopt::Long), so I don't want to add unknown options to my final hash.
    I want to pare down the entries in the hash to the mimimum amount of keys corresponding to only known parameters that i have been given.
    cheers though, Sorry the first draft of this reply was gibberish
    my %opts; my %locs = map { $_ => 1 } ('do', 'ny', 'kw'); my %sect = ('uid' => 1, 'email' => 'a', 'username' => 'a'); my $USAGE = qq( USAGE: perl launch.pl (-l=<location>)+ (-d=<data>)+ Where -l=<location> = [do|kw|ny] = one or more times -d=<data_type> = [uid|email|username] = one or more times ); die $USAGE unless (scalar(@ARGV) >= 2); GetOptions(\%opts, "l=s@", "d=s@"); die $USAGE unless (defined $opts{'l'}); die $USAGE unless (defined $opts{'d'}); %locs = map { $_ => $locs{$_}} grep defined $locs{$_}, @{ $opts{'l'} +}; # strips out keys from hash if %sect = map { $_ => $sect{$_}} grep defined $sect{$_}, @{ $opts{'d'} +}; # not requested by user die $USAGE unless scalar keys %locs > 0; die $USAGE unless scalar keys %sect > 0;
      Umm... you won't be. The only keys in %hash1 that are ever checked are values that exist in @ary. I'm assuming that @ary is the list of allowable parameters. That would mean that any values in %hash1 that didn't exist in @ary would never make it into %hash2. And, likewise, any values in @ary that don't exist in %hash1 don't make it into %hash2.