in reply to Variable variable?

It can be done, very easily, but it can lead to problems.
sub test { print "nothing\n"; } my $var = 'test'; &$var; # will call the sub, if you are not using strict.
This code will issue a run-time error if you are using strict.
However, if you do the same thing with objects, even with use strict, you can get away with it.
(This is one of the cases where Perl gives you splendid opportunities of shooting yourself in the foot.)
#!/usr/bin/perl -w use strict; package Camel; sub new { my $class = shift; my $self = bless {name =>'Jack Camel'}, $class; } sub who { my $self = shift; return $self->{name} } sub what { my $self = shift; return "a camel, can't you see that?"; } package main; my $camel = new Camel; for ('who', 'what') { print $_, "?\t", $camel->$_, "\n"; }
But you will be in trouble if you add an unmatched item to the list of variables, or you misspell one of them. Say, using ('what','woh'), the error will kick off at run-time only.
I very much agree with Juerd's advice. Don't do it.

Replies are listed 'Best First'.
Re: Re: Variable variable?
by Trimbach (Curate) on Mar 14, 2002 at 12:44 UTC
    True, but you won't get a compile-time error for non-existant method calls no matter how you call the bogus method. i.e.
    package main; my $camel = new Camel; print "Who", "?\t", $camel->woh, "\n";
    Compiles just fine... if you're gonna mistype the name of a method it doesn't matter whether the method name is symbolic or hard-coded (thought the typo on a symbolic reference may be far from the method call and harder to find.)

    Gary Blackburn
    Trained Killer