in reply to Re^2: PERL searching through a file
in thread PERL searching through a file
Hello ssimone, and welcome to the Monastery!
The code you’ve shown has some major problems:
First, it’s good to see you using warnings, but you should also use strict and declare each variable with my. This may look like a little extra work, but it will save you heaps of time and effort in the long run.
@params=<STDIN>;
Have a look at the output of this little script:
15:58 >perl -MData::Dump -wE "my @params = <STDIN>; dd \@params;" 1 2 3 ^Z ["1\n", "2\n", "3\n"] 15:59 >
Besides the fact that the user has to guess what is required, and remember to terminate with Ctrl-Z (or its equivalent), you’ll notice that each parameter has a trailing newline character. You should investigate Perl’s inbuilt chomp function (and also put the parameter input code inside a loop).
%numberoftimes={};
%numberoftimes is a hash variable, but {} is a scalar (a reference to an empty anonymous hash). To initialise a hash, use parentheses: %numberoftimes = (); — although a simple declaration (my %numberoftimes;) is all that’s needed here.
while(<FH>){
You can’t just use a filehandle (FH) without first opening it to point to a file:
open(FH, '<', $file) or die "Cannot open file '$file' for reading, stopped";
See perlopentut.
while(<FH>){ @lines=split("\n",$file); for $line(@lines){
There are two problems here. First, you want to split on each line, so giving the split function the name of the file makes no sense. Second, the syntax <FH> reads a line of text from the filehandle, so splitting on newlines again makes no sense. You want something like this:
while (my $line = <FH>) { chomp $line; for my $p (@params) { ... # use $line
if (index($line,$p)){
The builtin index function returns -1 on failure, and in Perl anything other than undef, 0, '0', or the empty string, is “true,” so the if clause won’t behave as you expect it to.
As toolic advised, you really need to read (or re-read!) perlintro and master the basics. The best way is to break your program down into its smallest parts, and work on each part until it does what you want and you understand how it works.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|