How to create a variable dynamically?

From: Artem Khodush (greenkaa_at_mail.ru)
Date: 04/28/04


To: beginners@perl.org
Date: Wed, 28 Apr 2004 12:03:51 +0400

Hello,

What are the ways to create a variable at run-time?

To be more specific, I'd like to not use eval in the def_x,
and keep "use strict 'vars'" in the code below:

package z;
use strict 'vars';

sub use_x
{
 eval( 'print "$x\n";' );
}

sub def_x
{
 # three ways to create $x:

 ${"z::x"}=123; # with this, use_x does not work with strict 'vars'
                     # - says 'variable $x is not imported'

 *{"z::x"}=\123; # and with this too.

 # is there any other way short of
 eval( 'use vars qw( $x ); $x=123;' ); # works

}

def_x;
use_x;



Relevant Pages

  • Re: best practice ... requires
    ... affect the way Perl parses your program, like strict and warnings). ... Do you know what calling a sub with & does? ... so you can see that my package is nested and I am now wondering how ...
    (comp.lang.perl.misc)
  • Re: multiple packages/classes in one file
    ... > so you can use globals under strict and not just lexicals. ... > this means global to the package that our is used in. ... > sub set_member ... > return $member; ...
    (comp.lang.perl.misc)
  • Re: CGI::Session with MySQL Driver
    ... >> Remember to run with strict turned on - I don't think you have with the ... >> script for you myself. ... Please, don't use "use vars". ... > sub execute { ...
    (comp.lang.perl.misc)
  • Re: our vs. use vars
    ... > except that use vars is backwards compatable. ... All these code snippets pass strict, and they each set the package ... a "use vars" declaration doesn't extend ...
    (perl.beginners)
  • Re: new in CGI::Session::Driver::postgredsql nonexisting
    ... i would suggest you turn on strict and warnings in this example.. ... or die "cannot prepare"; ... use CGI ':standard'; ... sub makeHTML ...
    (comp.lang.perl.misc)