in reply to Using variables in array names

What you want is called a 'symref' which is short for "symbolic reference", deprecated and disallowed under use strict 'refs';, which you should have on always (use strict; comprises the former).

You can still use them, if you really know what you're doing. But doing so amounts to mangling with a special hash, namely the symbol table. Use a "real" hash, instead and you're fine.

Replies are listed 'Best First'.
Re^2: Using variables in array names
by Anonymous Monk on Aug 05, 2005 at 12:45 UTC
    Use a "real" hash, instead and you're fine.
    I beg to differ. Using a 'real' hash subjects you to some of the same problems you face when using symbolic references. Biggest problem: making typos.
    use warnings; no strict 'refs'; my $point1 = 'valpt'; @{"use_$point1"} = ("foo", "bar"); ... my $var = 'valpt'; # Oops, typo. push @{"use_$var"}, "baz"; # Silently does the wrong thing. use strict 'refs'; my $point1 = 'valpt'; my %use; @{$use{$point1}} = ("foo", "bar"); ... my $var = 'valpt'; # Oops, typo. push @{$use{$var}}, "baz"; # Silently does the wrong thing.
    Using hash keys as variable names is only marginally better than using symbolic references. (The advantage mainly being you won't accidentely overwrite important package variables - which in this case, given there are no non-user variables starting with 'use', isn't a serious risk). You still got to be careful to be "fine".
      Howdy!

      Beg all you want. You won't get any... :)

      Using hash keys with variable names is so much safer than using symbolic references. The biggest problem with symbolic references is polluting the package namespace.

      If you have a data structure with elements whose name is only going to be known at runtime, you have little choice but to use a hash. It's the "right" data structure to use. You have to be responsible for the integrity of the way you manage your keys.

      yours,
      Michael
        The biggest problem with symbolic references is polluting the package namespace.
        I addressed that in my reply, and IMNSHO, that isn't the biggest problem. The vast majority of the problems I've seen when people use symbolic references (and when you give Perl classes you see a lot) stem from typos - not from "polluting" the package namespace.
      In fact they're almost the same, since under the hood, the creation of a symref populates the symbol table, which is 'only' a clever global hash anyway. It'd be interesting to know what the OP wanted to use the code for, since there may well be a nicer solution: the variable names look like they might be something to do with a multidimensional array, which could probably be handled in a tidier way.