Kirs Kringle
Kirs Kringle

Reputation: 929

comparing array to hashmap and deleting elements from hash in perl

I have a file being read in then changed into an array then counted and put into a hash table. I then read in another file that has stop words into an array. I want to take the array of stop words and compare it to the hash table and if a word from the stop words is a match then it deletes it from the hash table.

I'm curious as to what methods I could do to achieve this using perl. I wont post my code, because I'm refraining from having other people write my code. I just would like to know how I could go about this. If someone has a good website I could reference that could help.

Upvotes: 1

Views: 256

Answers (3)

Carlisle18
Carlisle18

Reputation: 389

I would initially use the simple loop solution but am also interested on other ways to do it. Maybe you could try this one?

my %new_table = map { $_ => $old_table{$_} } grep { not $_ ~~ @stop_words } keys %old_table;

1: It gets all the hash keys not in @stop_words using grep:

grep { not $_ ~~ @stop_words } keys %old_table;

2: Using those keys, it creates a new hash using map:

my %new_table = map { $_ => $old_table{$_} }

If you will be transforming them into arrays, you could use array_minus of Array::Utils

Upvotes: 1

gpojd
gpojd

Reputation: 23085

Try this:

my %table = some_sub_to_populate_table();
my @stop_words = some_sub_to_get_stopwords();
for my $stop_word ( @stop_words ) {
    delete $table{ $stop_word };
}

Upvotes: 3

pyr0
pyr0

Reputation: 377

this should work, too

open FH,"<".$PATH or die $!;
my $table={};
while(<FH>){
    $table->{$_}=VALUE
}
close FH;
open FH,"<".$PATH2 or die $!;
my @arr=<FH>;
close $FH;
delete $table{$_} foreach(@arr);

regards

Upvotes: 1

Related Questions