Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need some quick perl help 1

Status
Not open for further replies.

SgtB

IS-IT--Management
Joined
Oct 3, 2002
Messages
447
Location
US
This is probably pretty easy, but I'm still trying to teach myself perl....so bear with me. Here's the code I've written. Its just a little exercise to help me better understand hashes, subroutines...still covering the basics.

In the first 'while' statement at the bottom,
"%hash = &input;", how can I modify that %hash so that every time the &input is called it changes the hash instead of essentially overwriting it.
I've tried $hash{$key,$value} = &input, but only get strange characters in the result.

As of right now, the while loops are working, and the I'm prompted to enter as many names as I want, but the result is only the last key/value I entered. How would I write it so that the %hash would be modified every time the loop runs instead of a new %hash being created every time.

Code:
use strict;
my %hash;
my $key;
my $value;

sub input {
    my $employee;
    my $title;
    my %hash;
    print "Please type employee name.\n";
    chomp($employee = <STDIN>);
    print &quot;Please type employee title.\n&quot;;
    chomp($title = <STDIN>);
    %hash = ($employee => $title);
}

sub choice {
    print &quot;Would you like to add a person? yes or no.\n&quot;;
    chomp(my $response = <STDIN>);
    if ($response eq &quot;yes&quot;) {
        return 1;
    } else {
        return 0;
      }
}

while (&choice == 1) {
    %hash = &input;         # THIS IS THE PROBLEM LINE
}
while (($key, $value) = each %hash) {
    print &quot;$key is the $value.\n&quot;;
}

Any ideas?
Thanks! [smile] ________________________________________
Check out
 
Ok.

Couple of ideas for you.

Only declare %hash the once, you don't need to declare it inside your input() function.

Return two values from your input function, like this:

return($employee, $title);

and then call it like this:

while (&choice == 1) {
($emp, $ttle) = input();
$hash{$emp} = $ttle;
}

Also - If you add the line 'use warnings;' after 'use strict;' it will warn you about variables with the same name that &quot;hide&quot; one another, like when you declare %hash in a function when it's already defined. Mike

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top