Searching through file on Perl

perl, search

Solution

This is a more elegant approach, and I fixed the regex issue. `^` matched the start of a line.

open(LOGFILE, "input.txt") or die "Can't find file";

while(<LOGFILE>) {
   print "ERROR in line $.\n" if(/ERROR/);
}
close LOGFILE;

Or how about from the command line:

perl -n -e 'print "ERROR in line $.\n" if(/ERROR/);' input.txt

`-n` implicitly loops for all lines of input `-e` executes a line of code

To output to a file:

perl -n -e 'print "ERROR in line $.\n" if(/ERROR/);' input.txt > output.txt

While this is a good/simple example of using Perl, if you're using a Unix shell, grep does what you want with no need for scripting (thanks to TLP in the OP comments):

grep -n ERROR input.txt > output.txt

This is actually prints the matching line itself, with its line number.

Problem

Okay so I need to read in a file, go through each line and find where there is the string ERROR. This is what I have so far: ``` open(LOGFILE, "input.txt") or die "Can't find file"; $title = <LOGFILE>; $\=' ' ; while (<>){ foreach $title(split){ while (/^ERROR/gm){ print "ERROR in line $.\n"; } } } close LOGFILE; ``` So the problem that I have is that it only looks at the first word of each line. So if the input is boo far ERROR It won't register an error. any help would be greatly appreciated! I'm new to perl so please try and keeps things basic. Thanks!

Original source