in reply to Re: Interpolation in a hash key
in thread Interpolation in a hash key

I don't think $$hashvar{key} interpolates correctly as a dereferencer inside double quotes

Seems to work fine here. What happened when you tried it?

$ perl -le '$h = {one=>1}; print "$$h{one}"' 1
--
<http://dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re^3: Interpolation in a hash key
by pickledegg (Novice) on Jun 13, 2006 at 15:58 UTC
    Sorry chaps, I don't follow what you are doing there at all. I'm quite a novice.

    If I have:

    $$hashRecordPtr{'connection1_size1'}
    if I set $count to 3
    how can I replace the size1 for size$count and get $$hashRecordPtr{'connection1_size3'} ? Do you see what I'm getting at? I know you do as you are way above me in the perl stakes, I just don't understand your answer, sorry.

      Ok. Let's get back to basics then :)

      When you look things up in a hash, you use a string as the index. So your first example is the same as:

      $index = 'connection1_size1'; $$hashRecordPtr{$index};

      Do you follow that? The hash index is just any string value.

      But what we've done there is to now use a variable as the hash index. Which means that we can now be a bit cleverer.

      $index = "connection1_size$count"; $$hashRecordPtr{$index};

      So now we have a double-quoted string, and we've used the value of the variable $count within the string.

      So that effectively does what you want, but we can cut out the unnecessary $index variable and use the double-quoted string directly as the hash index.

      $$hashRecordPtr{"connection1_size$count"};

      Is that any clearer?

      --
      <http://dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg

        ... and of course, there are some times when we need to help the interpreter know when our variable begins and ends. In the example davorg gave you, $count fell at the end of your hash key (index). But suppose you wanted the $count to fall in the middle of your key, like this:

        $index = "connection$countsize";

        How would the interpreter know that you were referring to $count? You might have also been referring to $counts, $countsi, $countsiz, or $countsize. In such cases, you would put curly braces around the variable name to delimit it from the rest of the text.

        $index = "connection${count}size";

        No good deed goes unpunished. -- (attributed to) Oscar Wilde