Perl Aliases & Dynamically Scoped Variables

It seems Perl doesn’t allow you to create aliases to dynamically variables. Take the following:

{
  my ($foo, $bar);
  *foo = *bar;

  $foo = 10;
  $bar = 20;

  print "foo: $foo\n";
  print "bar: $bar\n";
}


What I want is for both $foo & $bar to equal 20, but, if you enable warnings, the warning clearly indicates the aliasing is taking place on global versions of $foo & $bar, not the ones scoped to our block.


Is there someway to do this that I’m missing?


Update: One for the friendly LA Perl Mongers pointed out I had flipped Dynamic & Lexical scoping and pointed me to Lexical::Alias.

4 Responses to “Perl Aliases & Dynamically Scoped Variables”

  1. Jeffrey Friedl Says:

    What is dynamic about the scope of any perl variable? All named variables are statically scoped (‘my’ variables are visible from within a specific lexical scope defined at compile time; global variables are visible from everywhere).

  2. Bill Says:

    I think using ‘local’ was refered to a dynamic as the value can depend upon a particular path of execution?

  3. Jeffrey Friedl Says:

    Oh, I guess I see what you mean. You’re not in good verbal form today, though, as the value of any non-constant variable tends to depend on the execution path, no? :-)

    “local” is an action which has no influence on the scope of the variable (on where in the code the variable is accessable from). It merely makes a copy of the current value and schedules that copied value to be put back at the close of the current lexical scope. You could consider that the varialble’s *value* has been dynamically scoped, an issue which seems unrelated to your original post about making aliases.

    I’m curious to look at Lexical::Alias to see how it was done. In pure Perl, I figure it’d have to be done with a tied variable or, gee, perhaps overloading could do it? It’s not something I ever recall having needed….

  4. Bill Says:

    Limiting my poor verbal form to just today is too kind. ;)

Leave a Reply