Hi, I'm new to Perl and just joined this site in hopes of having some questions answered. What I am trying to do is very simple, but I can't quite seem to get the hang of it. I want to ask the user to type in a filename, find the file, open it, search the file for a string and if the string is found store it in an array. Right now my program will do all of these things, however the match that's occurring is greedy, so it's finding all instances of each searchstring in the file. I only want it to store the string once in the array if it finds it, not multiple times for each time that it finds the string in the file. Below is an example of the code I'm using, perhaps someone can guide me as to how best to modify this so that it will stop searching once it has found the string once:
use strict; my ($Filename, @array, $searchstring, @stringsfound, @file); print "Please enter the name of the file:"; $Filename = <STDIN>; chomp($Filename); $Filename = "C:\\Perl\\".$Filename; open IN, $Filename or die "Could not open file $!"; @file = <IN>; close(IN); @array = ('file', 'this', 'dog', 'forward'); foreach (@file){ foreach $searchstring (@array) { if (m/(.*?)$searchstring/i) { push @stringsfound, $searchstring; } } } print @stringsfound;
Thanks in advance for any help on this, look forward to hearing what you have to say!

In reply to Match a string only once in a file by newbie2perl

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.