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

Hello! Is it possible to fill a hash in loop? Here is a code:

my @var_array = (1,2,3,4,5,6); my $var, my $r = 0; my %hash(); foreach my $var_p (@var_array){ $var = 3+$r; #hash with $var_p key and $var value: #%hash = ( # 1 => 3, # 2 => 4, # ... # 6 => 8, #); print "### $var\n"; $r++; }

Thank you for help!

Replies are listed 'Best First'.
Re: Filling a hash in loop
by Corion (Patriarch) on Apr 13, 2015 at 08:13 UTC

    Of course it is possible to fill the slots of a hash in a loop. Where are you encountering problems?

Re: Filling a hash in loop
by QM (Parson) on Apr 13, 2015 at 08:22 UTC
Re: Filling a hash in loop
by Anonymous Monk on Apr 13, 2015 at 09:01 UTC
Re: Filling a hash in loop
by AnomalousMonk (Archbishop) on Apr 13, 2015 at 15:39 UTC

    When you venture beyond assigning a value to a hash key (and doing it in a loop), you may find this useful: Perl Data Structures Cookbook (see also  perldocperldsc   from your friendly, neighborhood command line).


    Give a man a fish:  <%-(-(-(-<

Re: Filling a hash in loop
by jeffa (Bishop) on Apr 13, 2015 at 17:01 UTC

    Yes. If you replace the commented out code inside the for loop with this:

    $hash{$var_p} = $var;
    And then Dump out %hash then you will see that it contains the keys and values that you require. However ... there are much better ways to construct the hash that you want, such as:

    use strict; use warnings; use Data::Dumper; my @keys = (1 .. 6); my @values = map $_ + 3, 0 .. $#keys; my %hash; @hash{@keys} = @values; print Dumper \%hash;

    Hope this helps!

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)