Search code examples
arraysperlrandomhashhashref

How to pop from an array inside a hashref?


Brain getting foggy on this one. I wanted to take my dice game from using rand() to using a list of random values from random.org. I was able to retrieve the values just fine, I'm just hung up on the syntax to pop from the list.

Here's my function that's giving me fits:

sub roll_d
{
  return (pop($$dice_stack{@_[0]}));
  # Original code:
  #return (int(rand @_[0]) + 1);
}

Where $dice_stack is a pointer to a hash where the key is the dice type ('6' for d6, '20' for d20), and the value is an array of integers between 1 and the dice type.


Solution

  • $$dice_stack{@_[0]} - aka $dice_stack->{@_[0]} - is a VALUE in a hashref. As such, it will necessarily be a scalar and can't be a poppable-from-array.

    If the value is an array reference, you need to de-reference:

      return ( pop(@{ $dice_stack->{ @_[0] } }) );
    

    If it's NOT an arrayref, you need to access it in some other way.

    Also, this is starting to look golfish - at this point of line noisiness, I would recommend switching to more readable code (IMHO):

      my ($dice_type) = @_;
      my $dice_list = $dice_stack->{$dice_type};
      return pop(@$dice_list);