in reply to Re: How can I access package variables in a dynamic way
in thread How can I access package variables in a dynamic way

Thanks, but as I said I can't change the Person package right now. I know it's wrong but I'm stuck with it.
  • Comment on Re^2: How can I access package variables in a dynamic way

Replies are listed 'Best First'.
Re^3: How can I access package variables in a dynamic way
by haukex (Archbishop) on Feb 12, 2019 at 15:37 UTC
    I can't change the Person package right now. I know it's wrong but I'm stuck with it.

    If that really, really, really is the case, then here's enough rope to shoot yourself in the foot. This uses a trick to make $Person::addresses an arrayref whose elements are aliases to the original variables, so that you can modify elements of the array to modify the original variables. Consider this monkey-patching the Person package.

    $Person::addresses = sub{\@_}->( map { no strict 'refs'; ${"Person::address_$_"} } 1..3 );
      Unfortunately yes it really is. That does look like a solution - thanks.
Re^3: How can I access package variables in a dynamic way
by Corion (Patriarch) on Feb 12, 2019 at 15:37 UTC

    The best approach would be to create the appropriate hash yourself then:

    my %foreign_variables = ( address_1 => \$Person::address_1, address_2 => \$Person::address_2, address_3 => \$Person::address_3, # ... );
      I do like this, but in my actual use case (which I didn't mention, sorry) I don't know how many $nums there will be.

        In that situation, you will have to inspect the hash %Person:: and hope that all the variable slots have actually been assigned.