bennierounder has asked for the wisdom of the Perl Monks concerning the following question:

Hi Guys

Does anyone know how i can get a variable name to be changed depending on what info I pass. I have x number of months depending on the date range the user inserts. (month 1) (month 2) (month 3) etc. These are the column names but i need variables for each month. I want to do this

foreach (@columns) { if ($_ =~ /month(\d+)/) { $month . $1 = $whatever_value; } }

If $_ = month4, I want my variable name to be $month4. so, $month4 = whatever_value; Please let me know if you know a solution it would be very much appreciated.

Thanks Bennierounder.

Replies are listed 'Best First'.
Re: Changin the name of a variable in perl , with perl.
by Corion (Patriarch) on Sep 07, 2011 at 08:17 UTC
Re: Changin the name of a variable in perl , with perl.
by Ratazong (Monsignor) on Sep 07, 2011 at 08:46 UTC
Re: Changin the name of a variable in perl , with perl.
by LanX (Saint) on Sep 07, 2011 at 11:07 UTC
    better use either arrays or hashes (depending on the nature of your input):
    $month{$1}=$whatever_value; $month[$1]=$whatever_value;

    Cheers Rolf

Re: Changin the name of a variable in perl , with perl.
by morgon (Priest) on Sep 07, 2011 at 18:57 UTC
    As you've heard don't do it.

    But you can manipulate the symbol-table to create new variables like this:

    no strict "vars"; our $hubba = "whatever"; # create a new variable $bubba and make it an alias for $hubba *{$::{"bubba"}} = \$hubba; print $bubba; # prints "whatever"
    Note that this only works for variables that live in the symbol-table ("our"-variables) and not for lexicals (varibles introduced with "my").