Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Creating hash with my imput

by kejohm (Hermit)
on Aug 18, 2011 at 03:58 UTC ( #920852=note: print w/ replies, xml ) Need Help??


in reply to Creating hash with my imput

For starters, you should probably be using strict and warnings to catch any errors in your script.

You are only prompting for input once. Instead you need to get input inside a loop.

You code @DNA = $id doesn't split the input into ID and DNA automatically; you need to use the split() function to do that.

Here is an example that should do what you want (untested):

#!/usr/bin/perl usr strict; use warnings; my %hash; print "put ID followed by a comma with the DNA for that ID\n\n"; chomp(my $in = <STDIN>); while($in){ # Split the input on a comma into a maximum of two fields my($id,$dna) = split m/,/, $in, 2; $hash{$id} = $dna; print "Please enter another ID and DNA\n"; chomp($in = <STDIN>); } # Print hash contents while(my($key,$value) = each %hash){ print "$key -> $value\n"; }


Comment on Re: Creating hash with my imput
Select or Download Code
Re^2: Creating hash with my imput
by rolandomantilla (Novice) on Aug 19, 2011 at 01:36 UTC
    How would I, if I wanted to, use an if(statement) $in="exit"; then the program will exit??? By the way perlmonks you guys are genious

      If by exit you mean exit the loop and continue the script after the loop, you can use the last function to drop out of a loop, something like:

      ... while($in){ if($in =~ /exit/i){ last; } } # Code will continue here ...

      Here we are using a case-insensitive regular expression match to test for the user entering 'exit'. This means that the user can enter 'Exit', 'EXIT', eXiT', etc. and the loop will still terminate.

      This may not be necessay, since in my original example, if the user presses the ENTER key without typing anything, the input will be an empty string after chomp() has removed the newline, which, in Perl, evaluates to false, and the loop terminates.

      If, on the other hand, you mean exit from the script without, for instance, printing anything like in my original example, just replace last with exit in the example above.

        What I meant was exit the loop and print, sorry about the confussion. Although the extra code that you gave me just exits the loop and does not print the hash, how do I do this, byt the way thank you again

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2014-08-02 06:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Who would be the most fun to work for?















    Results (55 votes), past polls