+ 2

question about method split(',') in perl. [Solved]

Here is my code that is reading from file (perl_test.txt )which has following text E,V,E,R,Y,O,N,E,S,H,O,U,L,D,P,L,A,N,T,A,T,R,E,E my $str=""; open(data,'<','perl_test.txt'); while(<data>){ $str=$_; } close(data); print $str; my @arr=split(',',$str); $count=1; my %words; foreach my $j(@arr){ if(exists($words{$j})){ $words{$j}+=$count; } else{ $words{$j}=$count; } } my @keys_arr=keys %words; foreach my $f(@keys_arr){ print "$f,$words{$f}\n"; } The code above is counting occurence of each letter and printing it and i get output as : S,1 A,2 Y,1 N,2 V,1 E,4 R,2 H,1 P,1 D,1 U,1 O,2 T,2 E ,1 L,2 Tho I was expecting "E" to have a value 5 ,what am I missing here ? Ty!

31st Jan 2021, 10:54 AM
Abhay
Abhay - avatar
3 odpowiedzi
+ 4
Abhay I would go ahead and leave it as someone else may run into the same issue. Nice code btw, I just ran it here on SoloLearn.
31st Jan 2021, 5:06 PM
BroFar
BroFar - avatar
+ 3
Edit: as I was suspecting the problem to be a "\n" character ,after checking the string length and removing any whitespace and newline it works fine now. BroFar sorry for mentioning but just wanna ask if I should delete such question or not . Edit : the following regex removed any newline and whitespaces characters $str =~ s/\s+//g;
31st Jan 2021, 11:20 AM
Abhay
Abhay - avatar
+ 3
BroFar ty!.
31st Jan 2021, 6:41 PM
Abhay
Abhay - avatar