0
votes

I got this weird error that I don't understand. I am trying to fill a hash by an another hash if I find a word ($target) else, fill it by "undef".

# Parsing ...

    my $target;
    my $idx;
    my $gene_description_ref  = \@gene_description;

    # ... the functional annotation 

    $target = $tax_function . "_topblasthit";
    $idx = undef;

    # Get the index of "arth_topblasthit" in the array @gene_description

    foreach ( 0 .. $#gene_description ) {
        if ( index ( $gene_description_ref->[ $_ ], $target ) >= 0 ) {
            $idx = $_;
            last;
        }
    }

    if (defined $idx){

        my @result = func_formatting($gene_description[$idx]);
        $gene_hash{$gene_id}{Function} = $result[0];
        $gene_hash{$gene_id}{Accession} = $result[1];

    } else {    # Gene has no function 
        $gene_hash{$gene_id} = "undef";
    }

But I got this error:

Can't use string ("undef") as a HASH ref while "strict refs" in use at insert_genes_maker.pl line 283, line 7731.

any help please ?

1
A couple things. "undef" is a very misleading string, since it is defined and true. You need to use the bareword undef function to get an undefined value. An undefined value can then be used as a hashref, as you are apparently doing, and a hashref will magically appear due to autovivification. You could also instead assign an empty hashref {} explicitly, instead of undef. It's hard to say what is the correct thing to do without more context. - Grinnz
Btw, List::MoreUtils::first_idx provides what your 6-line-foreach+comment does, with a fairly descriptive name I think (it also has the first_index alias) - zdim
@zdim the error mentioned would not occur at that assignment, but would occur when that string is attempted to be used like a hashref somewhere else. - Grinnz
@Grinnz Ah, of course -- got mislead into thinking about how one could restrict a (part of a) hash or some such ... deleting that comment then, thanks - zdim

1 Answers

1
votes

Let me guess: further down in your program you have at line 283 something like this:

my $function = $gene_hash{$some_var}->{Function};

This will fail with the mentioned error message, because you have scalars (i.e. "undef") stored as values in your hash. You either need to protect access e.g.

if (ref($gene_hash{$some_var}) eq "HASH") {
    # access value as hash here
    ...

or use some other method to detect "unknown", e.g.

} else {    # Gene has no function 
    $gene_hash{$gene_id} = {};
}
...
if (exists $gene_hash{$some_var}->{Function}) {
    # access function key in here
    ...