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

Im trying to add a variable string to a string I'm using to index a hash. How can I do this? Any Ideas, I'd be grateful, cheers!!

Perl keeps telling my variable isn't initialised..

$hash{'colourred'} = 'RED'; $hash{'colourblue'} = 'BLUE'; $t='colour'; print $hash{"$t.red"} print $hash{"$t.blue"}

Replies are listed 'Best First'.
Re: Concatenating strings to use in a hash..
by Laurent_R (Canon) on Feb 08, 2015 at 18:19 UTC
    Anonymous Monk has given you two solutions to your problem, and yourself said you found out.

    This is not exactly what you asked for, but I just want to add that whenever I feel like concatenating words to build a hash key I tend to separate them with a separator. For example:

    $hash{'colour;red'} = 'RED'; $hash{'colour;blue'} = 'BLUE'; $t = 'colour'; print $hash{"$t;red"}
    It is IMHO clearer to read and it can help preventing subtle bugs when two different pairs of words lead to the same concatenated result. Suppose you have the words "abc" and "defgh" and the words "abcd" and "efgh": they end up being concatenated into the same key. With a well-chosen separator, this cannot happen. Even a simple space can sometimes make a good separator. And it solves naturally the problem that you had (at least with some proper separators such as ";" ",", "|", "-", space, etc.).

    Je suis Charlie.
Re: Concatenating strings to use in a hash..
by Anonymous Monk on Feb 08, 2015 at 15:58 UTC

    You are looking up the hash keys "colour.red" and "colour.blue". Use one of the following instead:

    print $hash{$t."red"}; print $hash{"${t}blue"};

    P.S. You just posted that you figured it out - it's best to also post your solution for the benefit of others.

Re: Concatenating strings to use in a hash..
by Anonymous Monk on Feb 08, 2015 at 15:55 UTC

    Figured it out, sorry for wasting your time and thanks for reading...