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

In my script I want to do something like ... $Person::address_$num

No, you don't :-) Full explanation at Why it's stupid to 'use a variable as a variable name'.

You almost always want a hash, or in this case an array, instead.

package Person; our @addresses; package main; my @lines; for my $i (0..$#Person::addresses) { push @lines, $Person::addresses[$i]; }

Replies are listed 'Best First'.
Re^2: How can I access package variables in a dynamic way
by bangor (Monk) on Feb 12, 2019 at 15:35 UTC
    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.
      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.

      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.