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:
- If you use warnings, perl will tell you when you declare a new variable that has the same name as one you already have (the first two lines of output from my script).
- When you start a new block, you can create a new version of a variable without perl giving you an error message (only two warnings for the four declarations).
- When a block goes out of scope, then the previously-hidden (masked) variable is available again. (The "Foo" at the end.)
- Immediately after creating a variable, it is undefined (the "use of uninitialized value" warning).
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. |