Reputation: 525
I want to fetch values from file info.log
and compare them to the string in $upper
.
This what I tried
my $upper = "S14";
open(my $file, "<", "info.log") or die "Can't open info.log: $!";
my $string = $upper;
while (<$file>) {
if ( ! -e $string) {
print " print here $string\n";
}
}
My file looks like this
ss1
ss2
ss3
ss4
ss5
ss6
ss7
ss8
the program outputs all the contents of the file. It should have not printed ss4
but it does?
Upvotes: 0
Views: 67
Reputation: 126722
First of all, you must always start every Perl program with use strict
and use warnings
.
As other people have noted, the -e
operator says whether a file of that name exists. It doesn't check whether one string appears witin another.
There are a few ways to do this. I would use a regular expression, but without knowing what sort of data you're dealing with, and to avoid confusing you, I have written a solution using the index
function which returns zero or more if the second string appears within the first.
use strict;
use warnings
my $file = 'info.log';
my $upper = 'S14';
open my $fh, '<', $file or die "Can't open '$file': $!";
my $string = $upper;
while (<$fh>) {
if (index($_, $string) >= 0) {
print "This file contains '$string'\n";
last;
}
}
Upvotes: 1
Reputation: 1941
If you simply want to just search for the matches, use grep its faster. Otherwise iterate through with a foreach.
my $upper="S14";
open(my $file, "<", "info.log") or die "Can't open info.log: $!";
my $string = $upper;
my @lines = <$file>;
my @matches grep { $_ =~ /$string/ } @lines; #searching *faster
foreach (@lines) { #iterating
chomp; #new line stuff
if($_ =~ /^$string$/is){
#stuff
}
}
Upvotes: -1
Reputation: 27265
The correct way to do this would be:
open (FILE, "< info.log") or die "error msg";
while (<FILE>)
{
if (/$upper/) {
MATCH CASE
}
}
Basically you loop through the file and check each line. Because you are reading the file in you don't need a variable ($_ is implied). on the check case.
Upvotes: 1