in reply to counting words in string
Hello Anonymous Monk,
Sorry I missed understood the question I will update it.
Another possible way (maybe not so efficient) is to use map and List::MoreUtils::uniq.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use List::MoreUtils qw(uniq); my $re = "iowq john stepy andy anne alic bert stepy anne bert andy ste +p alic andy"; my $i = 0; my %hash = map { ++$i => $_ } uniq split(/\s+/, $re); print Dumper \%hash; __END__ perl test.pl $VAR1 = { '6' => 'alic', '8' => 'step', '1' => 'iowq', '4' => 'andy', '2' => 'john', '7' => 'bert', '5' => 'anne', '3' => 'stepy' };
There is a similar question asked in the forum, see here Count duplicates in array..
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash; my $re = "iowq john stepy andy anne alic bert stepy anne bert andy ste +p alic andy"; my @names = split(/\s+/, $re); map($hash{$_}++, @names); # $hash{$_}++ foreach @names; # alternative instead of map print Dumper \%hash; __END__ $ perl test.pl $VAR1 = { 'bert' => 2, 'anne' => 2, 'alic' => 2, 'john' => 1, 'andy' => 3, 'step' => 1, 'iowq' => 1, 'stepy' => 2 };
Hope this helps, BR.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: counting words in string
by AnomalousMonk (Archbishop) on Aug 07, 2018 at 18:30 UTC |