0

Here is my code

my $filename = 'text.log';

my $items = "donkey";

open(my $fh, '<:encoding(UTF-8)', $filename) or die "Cant open";

while (my $contents = <$fh>)
{
        print "$contents";

        if ( $items =~m/$contents/)             
             { print "Found $contents";}            
        else { print "NOTHING\n";}
}
4
  • When do you think you'll print Found $contents? What you've written can run, but it requires caution; you probably won't ever see anything except NOTHING. In particular, you're creating a new regex for each line — which probably isn't what you intend. Commented Aug 10, 2017 at 5:07
  • @JonathanLeffler Yeah creating new regex is my main purpose to get it from the text file. But it didnt match anything even it should. Commented Aug 10, 2017 at 5:16
  • 2
    Why would it ever match donkey? The regex contains a newline which isn't in the $items string, so the regex will never match. Even if you chomped the input line, you'd seldom have $contents matching donkey. You could type donkey, or d..key or such like, but mostly, running text won't match $items. If you[re writing a primitive grep that hunts for donkey, then you have the regex expression back to front: you need if ($contents =~ m/$items/) as the condition. The explanation of what you're trying to do should be in the question, along with simple sample input (minimal reproducible example!). Commented Aug 10, 2017 at 5:18
  • thanks everyone <3 Commented Aug 10, 2017 at 5:39

1 Answer 1

1

Yes, but you'll need to remove the trailing newspace on each line ($contents =~ s/\n$//;):

#!/usr/bin/env perl
my $filename = 'text.log';
my $items = "donkey";
open(my $fh, '<:encoding(UTF-8)', $filename) or die "Cant open";
while (my $contents = <$fh>) {
    print "$contents";
    $contents =~ s/\n$//;
    if ($items =~ m/$contents/) {
        print "Found $contents\n";
    } else {
        print "NOTHING\n";
    }
}

Test:

$ cat text.log 
test
ok
donk
$ ./test.pl 
test
NOTHING
ok
NOTHING
donk
Found donk
Sign up to request clarification or add additional context in comments.

1 Comment

chomp $contents;

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.