tgolf4fun has asked for the wisdom of the Perl Monks concerning the following question:

Hello, another newbie here.

I have been working on a script for 3 days and cannot get this last part to work. I have two hashes %hash and %end.
the keys of %end are in %hash.
I want to delete the keys in %hash if they exist in %end this way when I print %hash after the iteration, it will contain the key/value pairs I want.
I then assign the %hash to an array and print the array.
I've used this code which give me "Use of Uninitialized.." errors
foreach $k(keys %hash){delete ($hash{$k}) unless exists $end{$_};}
I've tried to write this every way I can imagine, nothing works. Please oh please someone help me so I can get some sleep.

2004-11-12 Edited by Arunbear: Changed title from '3 days of frustration', as per Monastery guidelines

Replies are listed 'Best First'.
Re: Delete keys in hash if they exist in another hash
by davorg (Chancellor) on Nov 11, 2004 at 09:00 UTC

    I may be misunderstanding you, but I think you just want:

    delete @hash{keys %end};

    Here's a simple program that demonstrates it:

    #!/usr/bin/perl use strict; use warnings; my %hash = (one => 1, two => 2, three => 3); my %end = (two => 2); delete @hash{keys %end}; print "$_ => $hash{$_}\n" for keys %hash;

    By the way, I've taken my specification from your post where you say "delete the keys in %hash if they exist in %end", rather than your code which seems to do the opposite.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      Your code showed me what I was doing wrong. I've fixed this and my script works fine now. I kept skipping past the section on hash slices, now I know I should have stopped to read it. Your print command was also a big help. Thanks for your wisedom and patience for a newbie trying to make it up the ranks. :-)
Re: Delete keys in hash if they exist in another hash
by inman (Curate) on Nov 11, 2004 at 08:57 UTC
    Try:
    foreach $k (keys %hash){ delete ($hash{$k}) unless exists $end{$k}; }

    You were using $_ as the key to %end. You have not set $_ in the code you posted so it is unlikely to have a value that you want. This should clear the error.

      s/unless/if/ to be pedantic, but the clue is right of course.
      Thanks so much, what do they say about hind sight, anyway this worked. I just never put $k in $end{}. I can sleep now, and only hope that someday I can gain enough knowledge to help someone as you have I.