On a number of occasions, I have read that using variable names for variable definitions is a bad thing.

So why would one want to use them? Why are they available? (rhetorical question)

While playing with Perl (in an effort to learn it), I devised a subroutine that I found to be very useful. It's more complex than that shown here, but it's the same basic idea.

So, maybe there's another way to do the same thing, but, you know... tmtowtdi.

# Example of using variable names for variables, # that I find useful. #------------- # user defined code # ------------ my $some_var_list = var_from_env_var("list"); my $some_var_source = var_from_env_var("source"); my $some_var_other = var_from_env_var("other"); print "list=> $some_var_list\n". "source=>$some_var_source\n". "other=> $some_var_other\n"; # ------------ # my module # ------------ sub var_from_env_var { # could use this, or some other complex method # of determining the default value. my $list_def = $ENV{"LIST_VAR"} || $ENV{"LIST_VAR_DEPRECIATED"} || "other_list"; my $source_def = $ENV{"SOURCE_VAR"} || $ENV{"SECONDARY_SOURCE"} || "other_source"; # is there another way to use a variable to point # to a variable other than eval? my $input = shift; my $result = eval "\$$input"."_def"; return $result if (defined ($result)); return $input; }

Replies are listed 'Best First'.
Re: variables names used to define variables
by Abigail-II (Bishop) on Dec 11, 2003 at 01:21 UTC
    Why not just:
    my %vars = ( list => $ENV {LIST_VAR} // $ENV {LIST_VAR_DEPRECIATED} // "other_list", source => $ENV {SOURCE_VAR} // $ENV {SOURCE_VAR_DEPRECIATED} // "other_source", ); sub var_from_env_var { my $input = shift; $vars {$input} // $input; }
    No evals, no symbolic references, just plain and simple.

    Abigail

      Yeah, that ought to work.

      But sometimes just having fun is worth it too

      How else can I learn the strengths and weaknesses of a particular method if I don't try it out?

      But it all honesty, I didn't think of your way.

      Still new to all of the Perl Possibilities. (FORTRAN doesn't have hashes, pointers, foreach, or...)

        You may also find useful a post from liz: defined or: // and //=, because you will need to patch your perl to use the // operator...

        Ciao, Valerio

Re: variables names used to define variables
by jweed (Chaplain) on Dec 11, 2003 at 01:16 UTC

    In response to your second question, you don't need to eval. Use what's called a "symbolic reference" and do this:

    # v Assign a variable name to the $result variable my $result = "${input}_def"; return $$result if (defined ($$result)); # ^dereferencing return $input
    Check out perlref for more info.

    BUT (big but...) you should be using "real" or "hard" references. Because in general, Symbolic refernces are just a bit too much power for us mortals to handle, because you can muck stuff up so easily. Check out perlref again, but this time look for hard references info. The truth is, you could do all of this with a hash and references. Good luck!



    Who is Kayser Söze?
    Code is (almost) always untested.

      If you're going to use symbolic references (and hey, why not, they're cool :-) ), at least make it really obvious what you're doing;

      # v Assign a variable name to the $result variable return ${"${input}_def"} || $input;

      I've been using symbolic references so much recently I've been getting int the habit of using `use strict "vars", "subs";' instead of just `use strict;' :-)

      $h=$ENV{HOME};my@q=split/\n\n/,`cat $h/.quotes`;$s="$h/." ."signature";$t=`cat $s`;print$t,"\n",$q[rand($#q)],"\n";
Re: variables names used to define variables
by ysth (Canon) on Dec 11, 2003 at 02:42 UTC
    Why are they available? (rhetorical question)
    Not sure why you call it a rhetorical question, unless you are assuming everyone knows the answer. They exist because they allowed perl4 and earlier (which didn't have real references) to build complex datastructures and pass non-scalars by reference (though IIRC globs could also do the latter). They are also handy (but not necessary) for symbol-table manipulation. They also do a great job of allowing you to shoot yourself in the foot, hence the prohibition of using them under use strict.
Re: variables names used to define variables
by hardburn (Abbot) on Dec 11, 2003 at 15:37 UTC

    Symobolic refs are there because Perl needs them for certain things to work. For instance, class/object method calls are always done symbolically (even under strict 'refs'). Also, there are some tricks you can do for making a bunch of accessors/mutators at once using symbolic refs (which also happens to save memory).

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    : () { :|:& };:

    Note: All code is untested, unless otherwise stated

      Symobolic refs are there because Perl needs them for certain things to work.
      The main reason symbolic refs are in Perl is that before perl5, symbolic refs were the only refs you had.
      For instance, class/object method calls are always done symbolically (even under strict 'refs').
      Bullshit. There are no references to subs involved in finding methods when it comes to class or object method calling. Walking the @ISA tree has nothing to do with references.

      Perhaps you are confused about exporting subs (which is typically not done by OO classes). But then you are wrong again. Most exporting is done via the Export module, which uses neither 'strict' nor 'warnings'.

      Abigail

        Bullshit.

        Come on, stopping pussy-footing around and say what you mean man.


        Examine what is said, not who speaks.
        "Efficiency is intelligent laziness." -David Dunham
        "Think for yourself!" - Abigail
        Hooray!

        There are no references to subs involved in finding methods when it comes to class or object method calling.

        Yes there is. Otherwise, this code wouldn't work:

        $ perl -Mstrict -e ' package My::Foo; sub bar { my $class = shift; print "Calling $class->bar\n"; } package main; my $class = "My::Foo"; my $method = "bar"; $class->$method(); ' Calling My::Foo->bar $

        ----
        I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
        -- Schemer

        : () { :|:& };:

        Note: All code is untested, unless otherwise stated

        There are no references to subs involved in finding methods when it comes to class or object method calling.
        Not directly, but method invocation always involves symbol table lookups, which is just what a symref does.

        Makeshifts last the longest.