Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Getting values from a hash, using a string taken from a .csv file as the value

by choroba (Cardinal)
on Feb 17, 2015 at 17:18 UTC ( [id://1117021]=note: print w/replies, xml ) Need Help??


in reply to Getting values from a hash, using a string taken from a .csv file as the value

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.

لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1117021]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (9)
As of 2024-03-28 18:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found