in reply to How to count the total number of times the word 'the' and 'and' occur in 5 files i selected?

One way to do this is to use regular expressions, as in:
#!/usr/local/bin/perl -w use strict; open FILE, "<input.txt" or die "Blerch: $!\n"; local $/=undef; my $text=<FILE>; close FILE; print $text; my @ands = $text =~/\b(and)\b/ig; print scalar @ands; __END__ But now I know that twenty centuries of stony sleep were vexed to nightmare by a rocking cradle. And what rough beast, it's hour come round at last, slouches towards Betlehem to be born? And the world turned around the sun. 2
Doing this for multiple files and multiple words is left as an exercise for the reader.

Have a look at perlre for more information on regular expressions.

CU
Robartes-

  • Comment on Re: How to count the total number of times the word 'the' and 'and' occur in 5 files i selected?
  • Download Code

Replies are listed 'Best First'.
Re^2: How to count the total number of times the word 'the' and 'and' occur in 5 files i selected?
by Aristotle (Chancellor) on Jan 28, 2003 at 12:07 UTC
    How about not slurping?
    #!/usr/bin/perl -w use strict; my $count = 0; $count += /\band\b/g while <>; print "$count\n";

    Makeshifts last the longest.

      Of course :). BTW, your solution does not catch multiple 'and's in one line (you just count the number of lines 'and' occurs in at least once). The best of both our worlds would be:
      #!/usr/bin/perl -w use strict; my $count = 0; $count += () = /\band\b/ig while <>; print "$count\n";
      but you were probably aware of this :-)

      CU
      Robartes-

        Ouch, no, forgot - unfortunately, I'm not on a Perl-enabled computer right now, so I couldn't test it even if I wanted to.

        Makeshifts last the longest.

A reply falls below the community's threshold of quality. You may see it by logging in.