lingling has asked for the wisdom of the Perl Monks concerning the following question:

I honestly a new user of Perl. however,I dunno how to use it. i Hope that i can find someone to help me in this question. and if there has any person who can help me personally, can you please email me @elaine-ling@shaw.ca thanks really much. and since i really need help. thanks
  • Comment on How to count the total number of times the word 'the' and 'and' occur in 5 files i selected?

Replies are listed 'Best First'.
Re: How to count the total number of times the word 'the' and 'and' occur in 5 files i selected?
by robartes (Priest) on Jan 28, 2003 at 09:11 UTC
    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-

      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-

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: How to count the total number of times the word 'the' and 'and' occur in 5 files i selected?
by Gilimanjaro (Hermit) on Jan 28, 2003 at 21:25 UTC
    A probably slow but working solution:

    while(<>) { # loop thru all file arguments' lines for (split) { # split line on default separator (' ') $occ{$_}++; # increment counter for each word } } print $occ{'and'}+$occ{'the'}; # add occurrences

    I haven't actually checked if th