Discussion Locked

Perl hash question

0 helpful
6 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Learning Perl here, so bear with me... Have a hash that i need to delete the entry out of and am having problems doing that. Basically, I need to delete all entries from the hash that have values over 5,000,000. What I am trying to do is to find each entry and delete it. Does not work - I have made many changes but either the program will not compile or the hash entries are still there. Can gurus help? (in case somebody is wondering, I am trying to delete messages over 5Mb from a POP3 server...i have everything else but this - the most important part)

#!/usr/bin/perl
%messages = qw (1 342 2 4567 3 5999876 4 5768);
foreach $value (values (%messages)) > 5000000 {
delete $value.... #this is the line
}
print %messages, "\n";

6 replies

by timthetoolman

Hi,

The syntax you want looks something like this...

foreach $key (keys %HASH) {
delete $HASH{$key};
}

Which would delete all the entries.

Cheers,
Tim.

by bradleyr

Thank you. However, what is the syntax that deletes all keys which values are over 5000000? Thanks though.

by timthetoolman

I thought you were having problems with the "delete line"?

This was only an example to show you the syntax you need... Obviously you'll need your greater than check...

Cheers,
Tim.

by timthetoolman

...To help you even further - although its always best to learn these things by doing them yourself (with just a little tuition :-)...

try

foreach $key (keys %HASH) {
if ($key > 5000000) { delete $HASH{$key}; }
}

by bradleyr

sorry, the answer does not work.

Here is the code that does work:
#!/usr/bin/perl
%messages = qw (1 342 2 4567 3 5999876 4 5768);
foreach $value (sort { $messages{$b} <=> $messages{$a} } (keys(%messages))) {
if ($messages{$value} > 5000000) {
delete $messages{$value}; # ....
};
}

foreach $value (keys(%messages)) {
print "$value - $messages{$value}\n";
};

This discussion is closed to new replies.