I am trying to learn Perl here and the tutorial suggests the following code snippet after reading some file:
my $team_number = 42;
my $filename = 'input.txt';
open(my $fh, '<', $filename) or die "cannot open '$filename' $!";
my $found;
while(<$fh>) {
chomp;
last if($_ eq "Team $team_number");
}
die "cannot find 'Team $team_number'" if(eof $fh);
I don't quite understand why we need chomp, though. chomp removes the new line. So in each loop we remove the new line at the end of the line, but why? The script does throw an error if you remove the chomp, but I don't understand why.
I understand what chomping does, but I didn't get why that was necessary to match since we're already looping through all the lines - why would you then need to remove the new line? It was only after reading Kallol's post that I realised that eq would fail if not chomped, because the actual string that is looped, then, is Team 42\n. So that's why my question is different from other chomp questions: I didn't know why my code wasn't working without chomp and someone pointed me in the right direction.