in reply to Re^4: how to search for a string in a particular file?
in thread how to search for a string in a particular file?

tm86:

Each time you use "my" you declare a new variable. So at the line in question, you're declaring a new variable called $notfound, and then testing it to see if it contains "not found" before you ever set it to a value.

Here's a quickie to show you what I mean:

#!/usr/bin/perl use warnings; my $s='the quick red fox'; print $s, "\n"; my $s='Foo'; print $s, "\n"; { my $s="Bar"; print $s, "\n"; my $s; print $s, "\n"; } print $s, "\n";

When I run it, I get:

$ perl t.pl "my" variable $s masks earlier declaration in same scope at t.pl line +5. "my" variable $s masks earlier declaration in same scope at t.pl line +10. the quick red fox Foo Bar Use of uninitialized value $s in print at t.pl line 11. Foo

There are several things to notice here:

So you're close, but you need a couple tweaks:

#!/tools/packarch/public/perl/5.8.8/bin/perl use strict; use warnings; open(my $file, "<", "input.txt") or die "Can't open input.txt: $!"; my $string = "icecream"; my $notfound = ""; while (<$file>) { if (/$string/) { print "found string $string\n"; } else { $notfound = "not found"; } } if ($notfound eq "not found") { print "string not found\n"; }

As you can see, I put a declaration at the top and initialized it to "". Then removed all the extra declarations.

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^6: how to search for a string in a particular file?
by tm86 (Initiate) on May 30, 2012 at 04:31 UTC

    thanks! that worked like a charm. i understand the issue now... i seemed to be declaring it multiple times and no initialization. That will help my main code a lot!