I'm pretty sure that you don't want to do the thing that you're asking to do ... but it is possible.

approach 1: use an eval:

my %for_later; foreach my $name (@array) { eval <<"HERE"; my \$$name = new OBJ; do_stuff(\$$name); $for_later{$name} = \$$name; HERE }
approach2: use a global variable:
my %for_later; foreach my $name (@array) { no strict; ${$name} = new OBJ; do_stuff(${$name}); $for_later{$name} = ${$name}; }
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) { my $obj = new OBJ; do_stuff($obj); $for_later{$name} = $obj; }
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 $obj = new OBJ($name)
Now the object can remember its own name. --Dave

In reply to Re: dynamically creating variables named after the contents of an array by dpuu
in thread dynamically creating variables named after the contents of an array by gnu@perl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.