CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Help with Hashes

 



PerlBeginner1
New User

Apr 21, 2013, 5:02 PM

Post #1 of 3 (299 views)
Help with Hashes Can't Post

I need to do the following:

1) Make a hash using names and ages. A person's name is the hash and their value is their age.

2) Make some commands for the hash (ex: modify the array with input from a user)

3) When a duplicate name is generated, it would cause an access to the hash but not add a new element.



Here's my code:


Code
#!/usr/bin/perl 
use warnings;
use strict;

%hash = (Mike => '32', Kevin => '43', Dave => '19');

my $input;

while ($input != 0)
{

print "Enter something: ";

$input = <>;

}

$input = $Mike; //trying to put the CIN into the array.



Stuck on what to do next. Just started learning Perl.


g4143
Novice

Apr 21, 2013, 5:23 PM

Post #2 of 3 (298 views)
Re: [PerlBeginner1] Help with Hashes [In reply to] Can't Post

Won't it make more sense to set your loop up like...


Code
#!/usr/bin/perl 

use warnings;
use strict;

while ( <STDIN> )
{
chomp;
print $_, "\n";
}


A more complete solution would look something like this..

Code
#!/usr/bin/perl 

use warnings;
use strict;
use feature qw/state/;

my %hash = (Mike => '32', Kevin => '43', Dave => '19');

while ( <STDIN> )
{
chomp;
next if exists $hash{$_};

print "enter age->";
chomp(my $age = <STDIN>);
$hash{$_} = $age;
}

foreach(sort(keys(%hash)))
{
state $line_no;
print ++$line_no, ": $_ has a value->$hash{$_}\n";
}



(This post was edited by g4143 on Apr 21, 2013, 5:31 PM)


Laurent_R
Veteran / Moderator

Apr 21, 2013, 11:39 PM

Post #3 of 3 (282 views)
Re: [g4143] Help with Hashes [In reply to] Can't Post


Code
$input = $Mike; //trying to put the CIN into the array.


This should be something like this:


Code
chomp $input; 
$hash{$mike} = $input;


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives