Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Strict, cant use string as hash ref

by westy032001 (Novice)
on Dec 09, 2009 at 12:06 UTC ( [id://811903] : perlquestion . print w/replies, xml ) Need Help??

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

Helo Guys/Gals please could you help explain this error
"Can't use string ("CPU_USER_jwesvsf7") as a HASH ref while "strict refs" in use"
and if possible suggest an alternate way of doing it. Problem code:
use strict; my $server="jwesvsf7"; my $timestamp = "123433"; my $attribute="CPU_USER"; my $hashname =$attribute."_".$server; print "$hashname"; ${$hashname}{key} ="value" ;
many thanks. Thank you all for your responses!!

Replies are listed 'Best First'.
Re: Strict, cant use string as hash ref
by moritz (Cardinal) on Dec 09, 2009 at 12:15 UTC
    Instead of storing the name of a hash in a variable, use a nested hash:
    use strict; my %hash; my $server="jwesvsf7"; my $timestamp = "123433"; my $attribute="CPU_USER"; my $key =$attribute."_".$server; $hash{$key}{key} = 'value';
Re: Strict, cant use string as hash ref
by JavaFan (Canon) on Dec 09, 2009 at 12:09 UTC
    Well, you have a string "CPU_USER_jwesvsf7", inside a variable "$hashname", which you are treating as it were a (name of) a hash.

    That's a symbolic reference, which 'use strict' prevents you from using.

    Either don't use symbolic reference, or disable strict.

Re: Strict, cant use string as hash ref
by roboticus (Chancellor) on Dec 09, 2009 at 13:17 UTC

    westy032001:

    If you use moritz' solution, be sure to examine how you're using your hash. If you find yourself breaking up your current key on the '_' character later on, you might find it better to go ahead and have another key level or two, like:

    my ($server,$attribute) = ('jwesvsf7', 'CPU_USER'); $hash{$attribute}{$server}{key} = "value";

    ...roboticus