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

In reply to Re: find a string and count of its occurence in a text file by GrandFather
in thread find a string and count of its occurence in a text file by new@perl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.