johnirl has asked for the wisdom of the Perl Monks concerning the following question:

Hey Monks
if you had an array such as;

my @array =("var1", "var2", var3")

How would you convert it to a hash using user input or somesuch as the element and the above as a key?
Such as:

 %hash = ( "Info on var1", "var1", "Info on var2", "var2", "info on var3", "var3")

Thanks

j o h n i r l .

Sum day soon I'Il lern how 2 spelI (nad tYpe)

Replies are listed 'Best First'.
Re: array to hash
by Abigail-II (Bishop) on Aug 28, 2002 at 15:07 UTC
    %hash = map {do {print "Your information for $_: "; chomp (local $_ = <STDIN>); $_} => $_} @array;
    Abigail
Re: array to hash
by CubicSpline (Friar) on Aug 28, 2002 at 14:54 UTC
    If you want the values of @array to be the keys, then your example hash would look like this:

    %hash = ( "var1" => "Info on var1", "var2" =>, etc....);

    Without knowing any more about your problem than what you've stated, here's what I would do:

    my @array = ("var1", "var2", "var3"); my %hash; foreach my $item (@array) { $hash{$item} = "Info on $item"; # or <STDIN> for user input }

    Edit:
    Your use of the word key is somewhat confusing. Either you want to use the user input as key in a "many to one" mapping to the items in @array (which hotshot's answer will get you) or you want a "one to one" mapping where the keys are the items in @array and each one maps to some user input (which my answer attempts to do). Only you know what it is you need, so use that! :) ~CubicSpline
    "No one tosses a Dwarf!"

Re: array to hash
by hotshot (Prior) on Aug 28, 2002 at 14:53 UTC
    If I understood you right than try:
    my %hash; for $var (@array) { while (<STDIN>) { chomp; $hash{$_} = $var; } }


    Hotshot