vector40 has asked for the wisdom of the Perl Monks concerning the following question:
Hey, folks; new Perl user, just tinkering. This strikes me as something that should be easy, but it's behaving peculiarly.
What I want is a brief script that takes a text file, sifts through it according to a regex string, and count off how many times it finds said string. It prints this, telling me how many times it finds it (I've got it set up so that it reports back after each find, but it doesn't much matter; you could wait until it's done).
Observe: (beware, lots of painfully explicit stuff in here to aid debugging)
#!/usr/bin/perl -w use strict; use diagnostics; print "Do some regex now, shall we?\n"; print "Give me a file. Full path, please.\n"; chomp(my $filepath = <STDIN>); print "The filename is $filepath\n"; open FILE, "$filepath" or die "Couldn't open it. Error: $!\n"; my $count = 0; # Initialize the variable, just to be safe while (<FILE>) { if (/foo/) { $count++; print "$count so far.\n"; } } print "Program exiting\n";
Here's the problem. This sort of works... but only if each instance of the string is on a different line. This makes sense, I suppose; after all, it's taking each line individually. But if it's got four occurences of the string on one line, then it will count them all as one, which isn't too helpful.
Thoughts?
Thanks,
- Brandon
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Counting text strings
by Enlil (Parson) on Mar 04, 2003 at 05:58 UTC | |
by l2kashe (Deacon) on Mar 04, 2003 at 06:30 UTC | |
by vector40 (Initiate) on Mar 04, 2003 at 06:09 UTC | |
by Enlil (Parson) on Mar 04, 2003 at 06:46 UTC | |
by vector40 (Initiate) on Mar 04, 2003 at 07:55 UTC | |
by l2kashe (Deacon) on Mar 04, 2003 at 06:38 UTC | |
|
Re: Counting text strings
by Hofmator (Curate) on Mar 04, 2003 at 11:19 UTC |