CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Concatenating patterns and finding the number of occurences

 



PerlBeginner31
Novice

Apr 10, 2014, 10:35 PM

Post #1 of 2 (1800 views)
Concatenating patterns and finding the number of occurences Can't Post

The following code doesnt work correctly.

Text File:
HEYi dfjhfk HEY
HEYi
HEYi HEYi
HELLOi HELLOi
HELLOi
HELLOi HELLOi


Script:

use strict;
use warnings;
open FILE, "SAMP.txt" or die $!;

my %hash;
while (<FILE>) {
foreach ($_ =~ /(HEY|HELLO)(i)/g) {
my $wrd = $1.$2;
$hash{$wrd}++;
}
}

foreach my $key (keys %hash)
{
print "$key: $hash{$key}\n";
}


O/P:
HEYi: 8
HELLOi: 10

The o/p is double the actual count. Can someone help me point out the mistake in the code?

In my sample text I will have some strings common for 2 or more patterns. So I want to use OR operator for one part of the string. Please help.


BillKSmith
Veteran

Apr 11, 2014, 5:25 AM

Post #2 of 2 (1658 views)
Re: [PerlBeginner31] Concatenating patterns and finding the number of occurences [In reply to] Can't Post

Your inner loop runs twice for each match. (Once for the HE... and once for the i)


Code
use strict; 
use warnings;
#open FILE, "SAMP.txt" or die $!;
*FILE = *DATA;

my %hash;
while (<FILE>) {
foreach ( /(HE(?:Y|LLO)i)/g ) {
$hash{$_}++;
}
}

foreach my $key ( keys %hash ) {
print "$key: $hash{$key}\n";
}
__DATA__
HEYi dfjhfk HEY
HEYi
HEYi HEYi
HELLOi HELLOi
HELLOi
HELLOi HELLOi

Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives