- Jul 5, 2001
- 5,726
- 35
- 91
Edit: Before you continue, my program now works.
So I am new to perl and I am trying to split a text file in to a hash. It says I have an error on line 10. Anyone know why?
Edit: Now I have a new issue. My code is supposed to be doing to following. Gets the name of the file from the user, then takes that file and splits its contents into two hashes. Then the code is supposed to have to user enter one of three options. N for name # for number and . for exit. The problem I am running into now is when I enter in a option it just goes to the first argument in the if statement no matter what option I give it. I am not sure what I am missing. Can anyone give me some pointers? Thanks.
So I am new to perl and I am trying to split a text file in to a hash. It says I have an error on line 10. Anyone know why?
Code:
#!/usr/bin/perl
open (FILE, "name.txt");
print <FILE>;
close(FILE);
my %hash = ();
while(<FILE>){
($name, $number) = split(/ /, $_);
$hash($name) = ($number);
}
Edit: Now I have a new issue. My code is supposed to be doing to following. Gets the name of the file from the user, then takes that file and splits its contents into two hashes. Then the code is supposed to have to user enter one of three options. N for name # for number and . for exit. The problem I am running into now is when I enter in a option it just goes to the first argument in the if statement no matter what option I give it. I am not sure what I am missing. Can anyone give me some pointers? Thanks.
Code:
#!/usr/bin/perl
#user selects what file to use
print "File name to read in: ";
$filename = <>;
chomp $filename;
open (FILE, $filename);
#this bit of code splits the file into two hashes
while(<FILE>){
chomp;
($name, $number) = split(/ /, $_);
$namehash{$name} = $number;
$numberhash{$number} = $name;
}
close(FILE);
#this bit of code is supposed to take the option from the user and do the appropriate action
while (true){
print "Enter (N) for name and (#) for number search and (.) to exit";
$option = <>;
chomp $option;
if($option == "N"){
print "Enter number: ";
$input = <>;
chomp $input;
print $namehash{$input};
}
elsif($option == "#"){
print "Enter name: ";
$input = <>;
chomp $input;
print $numberhash{$input};
}
elsif($option == "."){
exit;
}
else{
print "You forgot to enter the option:";
}
}
Last edited:
