On Thu Aug 06 2009 @ 11:19, jet speed wrote:
> @array1 = ( D_101 D_102 D_103 D_104);
> @array2 = (0 1 2 3);
> 
> 
> How can i convert both of these arrays into %hash, assigining the
> @array1  as keys and @array2 as values.

    use warnings;
    use strict;
    my @array1 = qw/D_101 D_102 D_103 D_104/;
    my @array2 = (0, 1, 2, 3);

    my %hash = map { $array1[$_] => $array2[$_] } (0..$#array1);

This would work, but in practice if @array2 held literally numbers from 0
to the upper index of @array1, then it's unnecessary. You could do it
easily without a second array at all. If @array1 has numbers that aren't
simply the index, then you could do it as above. Otherwise, try this:

    my @array1 = qw/D_101 D_102 D_103 D_104/;

    my %hash = map { $array1[$_] => $_ } (0..$#array1);

Also you should always use warnings and strict to catch errors. You should
be seeing errors about how you're trying to initialize the two arrays
(barewords in @array1 and missing operators - the commas - in @array2).

> How can I recall only certain keys and their corresponding values of hashes
> ex : if D_103 then print " D_103 value is 2"
> ex :if D_101 then print "D_101 value is  0"

I'm not quite sure what you have in mind here, but in general printing a
key/value pair if you have the hash key in a variable (say $foo) is as easy
as this:
    
    print "The value of $foo is $hash{$foo}\n";

In this case, perhaps you narrow down the records you care about and then
put those into an array first:

    my @important_records = qw/D_102 D_104/;

    for my $item (@important_records) {
      print "The value of $item is $hash{$item}\n";
    }

  

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to