Gabelins
Gabelins

Reputation: 285

how to fix perl error: Type of arg 1 to each must be hash (not hash element)

I have a code that I wrote sometime ago. I tried to use it and I get this error Type of arg 1 to keys must be hash or array (not hash element) at line 18, near "} :" that I cannot figure out how to fix. The code is this

use strict;
use warnings;
use 5.12.0;

my $file = "test.txt";
open DATA, '<', $file or die "$!";

my %hash;
while(<DATA>){
    next if /^\s*$/m; # In case if you have empty lines.
    my ($key1,$key2,$val) = /^(\w)\|(\w) ([0-9.-]+)/;
    $val = int($val*10)/10; 
    $hash{$val}{$key1}++;
    $hash{$val}{$key2}++;
}
for (-9..9){
    $_ = $_/10;
    say "$_\t",ref $hash{$_} ? scalar keys $hash{$_} : '';
}

And my test.txt is

PBANLA_7 PBANLA_9 -0.976
PBANLA_2 PD39238 0.8
PD3_1 PD3_12 -0.76
PBANLA_13 PBANLA31 2563.654
PD3_91 PD3_342 0.1
PD3_23 PD3_84 1.5968E-05
PBANLA_3 PBANLA_2 108
PFC10_API0060 MAL13.1006 -1
PRA0005w MAL13.100 -0.17
PRA0005w MAL13.102 -0.17
PTA0005w MAL13.103 -0.17
PRA0005w MAL13.105 -0.175968E-06
PTA0005w MAL13.106 -0.17564
PRA0005w MAL13.107 -0.17
PRA0005w MAL13.108 30

The output I want is a count of the IDs (first and second column) that are in each bin. Suggestions are welcome! Thanks in advance, gabelins

Upvotes: 0

Views: 1770

Answers (1)

mob
mob

Reputation: 118605

In versions of perl older than v5.14 (edit: and newer than v5.22), the argument to keys must be a hash, not a hash reference. You must dereference your hash reference to make it a valid argument to keys.

%hash = (abc => 123);
$hashref = { def => 456 };

@k = keys %hash;       # ok
@k = keys $hashref;    # error in perl <v5.14
@k = keys %{$hashref}; # ok

Even in versions 5.14 through 5.22, keys HASHREF was considered "experimental" and subject to change in future versions.

Upvotes: 4

Related Questions