in reply to magic eval variables

To echo btrott, that's a symbolic reference which is quite confusing and easy to write incorrectly.

As I read it, there's an object name stored in $_. It's interpolated into pseudo-existence ($) and rereferenced (\), which lets you call its insert() method. Very ugly.

A better way to create variables at run time is by making them anonymous and storing them in some sort of data structure -- an array or a hash, for example. Novice programmers often tie themself up in loops trying to create uniquely named variables and store the names just to get at them later. Instead, learn how to use arrays and hashes and objects as containers, and save the sweating for the tricky stuff.

Replies are listed 'Best First'.
RE: Re: magic eval variables
by mdillon (Priest) on May 04, 2000 at 05:36 UTC
    i think that the "\$" is simply an escaped "$" inside double quotes, not a reference operator followed by a "$".
      Oops, you're right. Outsmarted myself. Thanks! That just goes to prove my earlier point -- this is a tricky technique, and it's easy to get lost.

      In effect, there must be a list of variable names somewhere. Let's assume a context like this:

      my @names = ("name", "rank", "serial_number"); foreach (@names) { (eval "\$$_")->insert('end', $dat{$_}); }
      For that to work, there must be objects $name, $rank, and $serial_number. As before, let Perl handle the bookkeeping:
      my %objects = ( 'name' => $name, 'rank' => $rank, 'serial' => $serial) +; foreach (@names) { $objects{$_}->insert('end', $dat{$_}); }
      Faster, more understandable, and won't muck about with your symbol table.