0

I have the below code. I am trying to find a match of 3 words in my log file and print the line if the match is found (only if all 3 words are present). It works fine if I hardcode the words (@typedefs) , but its not working if I have the same words in a array with strings (@typedefs_new). What is the mistake I am doing ?

my $str1="laa";
my $str2="faa";
my $str3="baa";

my @typedefs = qw(laa,faa,baa);
my @typedefs_new = ($str1,$str2,$str3);

my $file="/pathtofile/logfile.log";
open (FILE, $file) or die $!;

print "Output using typdefs_new array\n";
while ( my $line = <FILE> ) {
if ( any { $line =~ /$_/ } @typedefs_new ) {
    print $line;
  }
}

 print "Output using typdefs array\n";
while ( my $line = <FILE> ) {
if ( any { $line =~ /$_/ } @typedefs ) {
    print $line;
  }
}

logfile.log:

laa ferg gerg faa rgrebf baa abc def
fber rgreg rgre greg bgbg rghgr grhr

Output:

 Output using typedefs_new array
 laa ferg gerg faa rgrebf baa abc def
 fber rgreg rgre greg bgbg rghgr grhr

 Output using typedefs array
 laa ferg gerg faa rgrebf baa abc def
1
  • 1
    choroba pointed out why you're getting different results for your different arrays, but I'll add that if you want to only match lines that include all three keywords, you should be using all, not any. You should also change your regex to something like /\b$_\b/ to avoid matching words like blaa and faaa. Commented Jan 20, 2015 at 16:50

1 Answer 1

8

qw() separates words by whitespace, not by comma. So, your code is equivalent to

my @typedefs = ( 'laa,faa,baa' );

warnings should have told you:

Possible attempt to separate words with commas
Sign up to request clarification or add additional context in comments.

1 Comment

if that were the code they are actually using though, they wouldn't have got the output they say

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.