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

Why there isn't any function in perl that deletes everything in a hash, removes keys, and deletes it such that it is like just it was declered. How can i do this? The following code shows how I create the hash.
my %load_number_hash = (); foreach(@load_array){ $load_number_hash{$_} = $_; }
when I try to recreate the hash I get following error message:
Use of uninitialized value in hash element at ...

Replies are listed 'Best First'.
Re: Hash problem
by Abigail-II (Bishop) on Jun 27, 2003 at 13:26 UTC
    %load_number_hash = (); # Deletes everything.

    Abigail

Re: Hash problem
by adrianh (Chancellor) on Jun 27, 2003 at 13:29 UTC
    Why there isn't any function in perl that deletes everything in a hash, removes keys, and deletes it such that it is like just it was declered

    Either of the following will do it:

    undef %hash; %hash = ();

    The error you gave doesn't make a lot of sense without some context.

Re: Hash problem
by tcf22 (Priest) on Jun 27, 2003 at 13:34 UTC
    You can use %load_number_hash = (); to clear the hash. Also delete will remove one key at a time. Here's an example.
    use strict; use warnings; use Data::Dumper; my @load_array = (0..9); my %load_number_hash = (); foreach(@load_array){ $load_number_hash{$_} = $_; } print Dumper \%load_number_hash; delete $load_number_hash{3}; print Dumper \%load_number_hash; %load_number_hash = (); print Dumper \%load_number_hash;
    Gives you the following output:
    $VAR1 = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9 }; $VAR1 = { '0' => 0, '1' => 1, '2' => 2, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9 }; $VAR1 = {};
Re: Hash problem
by artist (Parson) on Jun 27, 2003 at 13:33 UTC
    use strict; use warnings; my @load_array = (1,2,3); my %load_number_hash = (); foreach(@load_array){ $load_number_hash{$_} = $_; } %load_number_hash = (); print $load_number_hash{1};
    If you mean above, you are right.. It gives me warning. IMHO, it is correct. You can possibly store your hash-keys in another hash. In order to be defined for the hash $hash{$key} is necessary which is not preserved after 'deletion' or undef operation on hash items

    artist

Re: Hash problem
by BrowserUk (Patriarch) on Jun 27, 2003 at 13:53 UTC

    Try printing @load_array just before the loop, or the value of $_ just inside the loop. I bet that you have one or more undefs in there somewhere.

    Quite how you got to asking this question from that error message I'm confused about. What did you think that error meant was happening?


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller