user2941526
user2941526

Reputation: 497

Creating Incremented Values for a Hash in Perl

I am new to perl and I'm trying to create a hash based on some user input. I want the keys of the hash to be between a specific range with an increment of each key. At this point I need the values of each key to be 0.

At the minute, my code is:

my %hash;
foreach (my $increm = $lowerbound; $increm <= $upperbound; ++$binsize) {

        push ($hash {$increm}, 0);

}

Example values could be:

$lowerbound = 500
$upperbound = 600
$binsize = 1

I get an error of "Not an ARRAY reference", what is the problem and where am I going wrong?

Thank you in advance!

Upvotes: 1

Views: 1174

Answers (4)

onionpsy
onionpsy

Reputation: 1522

Push is for array, you can do it like this :

my %hash;

my $lowerbound = 500;
my $upperbound = 600;
my $binsize = 1;

foreach (my $increm = $lowerbound; $increm <= $upperbound; $binsize++) {
    $hash{$increm} = 0;
}

Upvotes: 0

ikegami
ikegami

Reputation: 386331

First of all,

++$binsize

should be

$increm += $binsize;

push has two syntax:

 push @array, LIST
 push $array_ref, LIST

You're using the second, which expects a reference to an array, but you're passing undef instead. Fix:

push $hash{$increm} ||= [], 0;

would do the trick. That said, that syntax is "highly experimental" and doesn't work with all reference to arrays. I suggest you stick to the traditional syntax.

push @{ $hash{$increm} ||= [] }, 0;

But thanks to autovivification, that simplifies to

push @{ $hash{$increm} }, 0;

But why are you using push at all? You only ever assign one value per key, so the push is equivalent to the following:

$hash{$increm} = [ 0 ];

Actually, it's questionable whether you want $hash{$increm} to be an array reference at all. Do you simply want the following?

$hash{$increm} = 0;

Upvotes: 3

edem
edem

Reputation: 3272

You may do so:

perl -MData::Dumper -e 'for (1..5) { $a->{$_} = 0 }; print Dumper $a'

$VAR1 = {
          '4' => 0,
          '1' => 0,
          '3' => 0,
          '2' => 0,
          '5' => 0
        };

Upvotes: 0

You push onto arrays. Just use a simple assignment like this

$hash{$increment} = 0 ;

Also, don't leave a space between the end of $hash and the curly braces.

Upvotes: 0

Related Questions