in reply to find a string and count of its occurence in a text file

There is a lot needless code in your sample, and a couple of foibles. Assuming you want to do something other than just printing out the contents of the matching line, something like the following sample may be what you are after:

use strict; use warnings; my $fileContent = <<DATA; abc:AB CD:100 def:DE FG:101 ghi:GH IJ:102 abc:AB CD:100 ghi:GH IJ:103 DATA open FILE, '<', \$fileContent; while (<FILE>) { chomp; # chomp not chop. $_ is default so omit my @elements = split /:/, $_; next unless $elements[0] eq 'abc'; print "Matched: ", join ('|', @elements), "\n"; } close FILE;

Prints:

Matched: abc|AB CD|100 Matched: abc|AB CD|100

Note that for purposes of the sample the "file" is actually just a string, although Perl allows it to be opened and manipulated as a file.

Generally it is a bad idea to rely on the contents of $_ remaining unaltered over more than a couple of lines of code. You are better to use an explicit variable in such cases so that the intent of the code is clearer and so that the value doesn't get altered in unexpected ways.

Use the three parameter open to make intent clearer and use safe (what happens if the file name starts with '>' in your sample?).

grep on a single element can be replaced with an if.


Perl is environmentally friendly - it saves trees