If the line contains only the string
apple, and you split it on comma (line 16), the newline at the end of the line stays in
$line[0]. Therefore, the hash doesn't return anything for the key. Use
chomp to remove the newline:
#!/usr/bin/perl
use warnings;
use strict;
my %fruit;
open my $FRUIT, '<', 'fruit.csv' or die $!;
while (<$FRUIT>) {
my @line = split /,/;
my($fruit_name, $number) = @line;
$fruit{$fruit_name} = $number;
}
close $FRUIT;
open my $FRUITNAMES, '<', 'fruit_names.csv' or die $!;
while (<$FRUITNAMES>) {
chomp;
my @line = split /,/;
my $thefruitsname = $line[0];
warn ": $thefruitsname";
my $thenumber = $fruit{$thefruitsname};
print "the number of $thefruitsname is $thenumber\n";
}
Also use indentation, 3 argument open + or die, and strict as shown in the script.