Here's an answer that shows why I like eval -- not because it's efficient, safe, or even clean, but because you can occasionally throw off the shackles of other computer languages and do stuff at runtime you'd never thought possible.

Warning: This is almost definitely not the best way to approach your problem, and if you use it in production code you're more courageous than I -- but it's a tool and I know how to do it. Sufficiently warned:

#!/usr/bin/perl -w use strict; BEGIN { my @packages = qw(test test2); my @vars = qw(first second); populate(); sub populate { my $text = ''; foreach my $package (@packages) { foreach my $var (@vars) { $text = '$' . $package . '::' . $var . ' = 1;' . "\n"; print $text; eval $text; } } } } print "test:\t$test::first\t$test::second\n"; print "test2:\t$test2::first\t$test2::second\n";
You could also create $text to eval that contains your package statement and use vars statements or my statements as you see fit.

There's another way, using symbolic references. That's also generally considered a bad idea, because it's easy to cause flaming death with a typo:

#!/usr/bin/perl -w use strict; my @vars = qw(one two three); package main; my ($one, $two, $three) = (1 .. 3); { no strict 'refs'; foreach my $var (@vars) { *{"test::$var"} = $var; } } package test; print "One: $one\tTwo: $two\tThree: $three\n";

In reply to Re: Variable Package Names? by chromatic
in thread Variable Package Names? by swiftone

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.