Perl: Understanding @allwords

Hi guys,

Here is the code:

my @allwords = ();
my %seen=();
foreach my $curr (@allwords) {
$seen{$curr} = 1;
}
@allwords = keys %seen;

my question is: what will @allwords now contain, or how would the entries in the @allwords array be different after this manipulation?

Thank you!!

I am trying to understand more about this array.

your array @allwords is empty hence foreach loop would never execute
you will still have an empty hash after the foreach loop
thus the last statement won't cause any difference and @allwords would still be empty

if you had some entries in @allwords say,

 
my @allwords = qw/a b c d a/;
my %seen=();
foreach my $curr (@allwords) {
$seen{$curr} = 1;
}
@allwords = keys %seen;

the foreach loop will assing each element of the array @allwords as a key to %seen hash and each key would have 1 as it's value i.e.,

 
$seen{$a}=1
$seen{$b}=1
$seen{$c}=1
$seen{$d}=1
$seen{$a}=1 #already exists so would be discarded

however, on the last iteration when $curr is a again, your hash already has a key a with value as 1, so it won't allow a duplicate entry and last element of @allwords would be discarded

 
@allwords = keys %seen;

keys %seen would return ('a','b','c','d') and assign it to @allwords

hence, in short your code here would remove any duplicate entries in an array
Njoy!! :wink:

1 Like

You can achieve the same result with map:

my %seen=map { $_ => 1 } @allwords; 
@allwords= keys %seen;
1 Like

THANK YOU!!!

---------- Post updated at 11:39 ---------- Previous update was at 11:39 ----------

THANK YOU!!:b: