I'm not sure you want to do what you are asking for. You could do

Update: Arien++ for bringing the error in the line below to my attention. I'd like to claim it was deliberate to prevent the unwary from doing this. It wasn't. It's just something I never do. I'm leaving it as-is with the flag.

my @array = qw( foo bar baz ); for (@array) { eval "$_ = 'value'"; # Error here!!! }

You now have three vars $foo='value'; $bar='value'; $baz='value';

but unless you know what these names are when you write your script--in which case why bother doing this at all--you have no convenient way of using these vars?

I think what your trying to acheive is an associative array or in Perl's terms, a hash. In which case, to set up a hash from the values of an array, use (for example)

#name your hash my %hash; #autovivify elements with names from the array.. #using undef simply means they will all be undef. # (all but the first one would be anyway, this just keeps things consi +stant). @hash{@array} = undef; # then to use your named array elements # eg. keyboard or web page. Assume we get the string 'foo' my $varName = getVarNameFromSomeWhere(); # then to use it $hash{$name} = 'we just gave $hash{foo} this as its value'; #and to print it print $hash{$varName}, "\n";

I hope I read your question correctly, and this is useful, if not, post a reply explaining a little (lot) more of what it is you are trying to achieve.


Well It's better than the Abottoire, but Yorkshire!

In reply to Re: dynamically creating variables named after the contents of an array by BrowserUk
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.