Why does my file content/user input not match? (missing chomp canonical) [duplicate]
I'm reading from a file/STDIN
and looking for a specific value:
use strict;
use warnings;
my $find = 'def';
while (<DATA>) {
if ($_ eq $find) {
print "Found: $_\n"; # Never reached!
}
}
__DATA__
abc
def
xyz
Why is the condition never matched?
Solution 1:
Data::Dumper
can be used to more closely examine the variables:
use Data::Dumper;
local $Data::Dumper::Useqq = 1;
print Dumper $_, $find;
Outputs, e.g.
$VAR1 = "def\n";
$VAR2 = "def";
You have to remove the \n
character that <DATA>
reads into $_
. The simplest way to do it is the chomp
function
use strict;
use warnings;
my $find = 'def';
while (<DATA>) {
chomp;
if ($_ eq $find) {
print "Found: $_\n"; # Never reached!
}
}
__DATA__
abc
def
xyz