in reply to returning matched word from string

open (FILE, 'acrolist.txt'); my @lines = <FILE>; my @data; foreach my $line (@lines) { if ( $line =~ /$teststring/ ) { print "You have a MATCH: $1\n"; push @data, $line; } } print @data;

Is this what you are trying to do?

<(^.^-<) <(-^.^<) <(-^.^-)> (>^.^-)> (>-^.^)>

Replies are listed 'Best First'.
Re^2: returning matched word from string
by toolic (Bishop) on Jul 23, 2008 at 00:53 UTC
    A few comments:
    • You need to use capturing parentheses in your regular expression, /($teststring)/, if you want to use $1
    • use warnings;
    • Check the status of your open
    • Consider using a lexical filehandle and the 3-argument form of open: open my $fh, '<', 'acrolist.txt'
    • close the file

      You're absolutely correct. All I did was copy-paste the code from one of my scripts (explaining the first, second, and last bullet) and change a few details. The other two points are more laziness of mine.

      I'll update my code appropriately. Thanks for the comments.

      <(^.^-<) <(-^.^<) <(-^.^-)> (>^.^-)> (>-^.^)>
Re^2: returning matched word from string
by monaghan (Novice) on Jul 23, 2008 at 00:40 UTC
    hmmm, that looks really close to what I want but $line isn't matching anything in $teststring. acrolist.txt looks like: firstword secondword CPLD lastword
      So you want to match the string if any of the words on the line match? Did you want to know if "each word matched" or if "any word matched"?
      # Any word matched while (<$words_fh>) { my $re = join '|', map quotemeta, split; if ( $teststring =~ /($re)/ ) { print("$teststring contains $1\n"); } }
      # Each word matched while (<$words_fh>) { for my $word ( split ) { if ( $teststring =~ /\Q$word/ ) { print("$teststring contains $word\n"); } } }
        That first method did the trick! Thank you very very much for your help everyone. This was my first time on PerlMonks and it was fast and easy. I think now I need to convert this array of acronyms to a hash.

      Oh, I see. You are simply comparing the two strings. I am positive there is a more efficient way to do this, but for a makeshift fix you could put each word of $teststring into an array. Then, foreach element, test to see if it matches $line in the aforementioned array.

      <(^.^-<) <(-^.^<) <(-^.^-)> (>^.^-)> (>-^.^)>