in reply to dynamically creating variables named after the contents of an array
approach 1: use an eval:
approach2: use a global variable:my %for_later; foreach my $name (@array) { eval <<"HERE"; my \$$name = new OBJ; do_stuff(\$$name); $for_later{$name} = \$$name; HERE }
These should both work, but would be pretty silly for the scenario you describe. There is no benefit from naming a variable at run-time except in very arcane situations. It would be much better to do the simple:my %for_later; foreach my $name (@array) { no strict; ${$name} = new OBJ; do_stuff(${$name}); $for_later{$name} = ${$name}; }
A couple of final notes: you'll noticed that I used $name in my examples, not $_ as you requested. You could use $_; but I don't recommend it. If you do want your objects to be named, you could always pass the name to the ctor:my %for_later; foreach my $name (@array) { my $obj = new OBJ; do_stuff($obj); $for_later{$name} = $obj; }
Now the object can remember its own name. --Davemy $obj = new OBJ($name)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: dynamically creating variables named after the contents of an array
by gnu@perl (Pilgrim) on Sep 06, 2002 at 18:37 UTC |