How to take hash values from terminal in perl

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rammohan
    New Member
    • Feb 2014
    • 4

    How to take hash values from terminal in perl

    Hi to all ! I'm new to this forum an as well as Perl scripting . My question is how to take Hash values from user using terminal in Perl.

    my code is :
    my%inputline = <STDIN>;
    print %inputline;


    it showing some error
    Odd number of elements in hash assignment at until.pl line 199, <STDIN> line 1.
    ram 47 nasdfi 47 klsdjf 258 dshafa 639
    Use of uninitialized value $inputline{"ram 47 nasdfi 47 klsdjf 258 dsha"...} in print at until.pl line 202, <STDIN> lin
  • miller
    Recognized Expert Top Contributor
    • Oct 2006
    • 1086

    #2
    <STDIN> is always going to return you a single value. Hashes take key value pairs, so you'd need at least 2 values to initialize your hash. You could do this properly in one of two ways, you could either get the key value pairs in separate input statements, or you could parse the single input and separate the values. Given that you're new, I'd suggest doing the former:

    Code:
    use Data::Dumper;
    
    use strict;
    use warnings;
    
    my %hash;
    
    while (1) {
    	print "Enter the hash key (nothing to end): ";
    	my $key = <STDIN>;
    	chomp($key);
    	last if $key eq '';
    
    	print "Enter the hash value matched with $key: ";
    	my $val = <STDIN>;
    	chomp($val);
    	
    	$hash{$key} = $val;
    }
    
    print Dumper(\%hash);
    - Miller

    Comment

    Working...