Question:
Given a file, count the word occurrence (case insensitive)
Answer:
open(FILE,"filename"); @array=<FILE>; $wor="word to be found"; $count=0; foreach $line (@array) { @arr=split (/s+/,$line); foreach $word (@arr) { if ($word =~ /s*$wors*/i) $count=$count+1; } } print "The word occurs $count times"; Source: CoolInterview.com
Answered by: Anjali gupta | Date: 6/11/2008
| Contact Anjali gupta
$infile='txt';
open INFILE,"$infile" or die ;
while(<INFILE>) { chomp; $r++ for $_ =~/the_word/g; } print "r $r
";
close INFILE; Source: CoolInterview.com
Answered by: Ranjit Divakaran | Date: 10/27/2008
| Contact Ranjit Divakaran
open(FILE,"file.txt"); @array=<FILE>; $count=0; foreach $line (@array) { chomp($line); @a=split(//,$line); foreach $line1 (@a) { print"$line1"; if( ($line1 !~ m/
/) ){ if ($line1 !~ m/s/) { $count+=1; } }
}
}
print"
$count"; Source: CoolInterview.com
Answered by: shivakumar shreeshail | Date: 11/17/2009
| Contact shivakumar shreeshail
@a = "My name is Khan"; foreach $c (@a) { @b = split ('s+', $c); print scalar @b; } Source: CoolInterview.com
Answered by: vasudevan D | Date: 3/18/2010
| Contact vasudevan D
Try this, it will work :) #!/usr/bin/perl $="
"; open(FILE,"filename"); @array=<FILE>; $count=0; foreach $line (@array) { @arr=split (/[ ]+/,$line); $count+=@arr;; } print "The word occurs $count times"; Source: CoolInterview.com
Answered by: Abhishek | Date: 3/31/2010
| Contact Abhishek
open(FILE,'files.txt');
my @arr=<FILE>;
foreach (@arr){ push(@words,split(/ /,$_)); }
print (scalar @words); Source: CoolInterview.com
Answered by: sanz | Date: 5/26/2010
| Contact sanz
open FH1, "file1" or die "Cannot open file file1 : $!"; @array=<FH1>; foreach $l (@array) { push(@arr1,split(/s+/,$l)); } my %hash1; foreach $y (@arr1) { $c=1; foreach $z (@arr1) { if ($y eq $z) { $hash1{$y}=$c++; } } }
foreach $key (keys %hash1) { print "$key --> $hash1{$key}
"; } Source: CoolInterview.com
Answered by: Sarala | Date: 8/18/2010
| Contact Sarala
$infile='Search file name'; open INFILE,"$infile" or die ; while(<INFILE>) { chomp; $r++ for $_ =~/Searchword/g; } print "r $r ";
close INFILE; Source: CoolInterview.com
Answered by: Bimlesh Sharma | Date: 8/28/2010
| Contact Bimlesh Sharma
If you have the better answer, then send it to us. We will display your answer after the approval.
Rules to Post Answers in CoolInterview.com:-
- There should not be any Spelling Mistakes.
- There should not be any Gramatical Errors.
- Answers must not contain any bad words.
- Answers should not be the repeat of same answer, already approved.
- Answer should be complete in itself.
|