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

Would anyone know how to go about writing a chunk of code which would take a string, say var1=test, which was passed as a command argument (./test.pl "var1=test"), and automatically create a variable named "$var1" and assign it the value of "test"? Or is this totally impossible?

Replies are listed 'Best First'.
RE: Variable auto creation
by t0mas (Priest) on Sep 28, 2000 at 10:06 UTC
    This is bulit in functionality :) Have a look at the -s flag in perlrun...

    You can pass arguments like this to perl like:

    ./test.pl -var1=test

    where ./test.pl is something like:
    #!/usr/bin/perl -s if ($var1) {print $var1};


    /brother t0mas
Re: Variable auto creation
by mirod (Canon) on Sep 28, 2000 at 10:06 UTC

    You could do this:

    #!/bin/perl -w my( $_var, $_val)= split /\s*=\s*/, $ARGV[0]; die "can't use $_var as a variable name" if( $_var=~ /^_va[rl]$/); ${$_var}= $_val;

    This is higly unsafe though, you cannot use strict (at least not strict 'refs') and you risk overwriting one of you existing variables.

    Why not just use a hash:

    #!/bin/perl -w use strict; my( $_var, $_val)= split /\s*=\s*/, $ARGV[0]; my %hash=( $var => $val);

    If you call both snippets with foo=bar as argument The first one lets you use $foo and the second one $hash{foo}.

      The second snippet works great, but im not so familiar with hashes, is there any function like a push() for hashes? The code only works with one command line argument, i would like to be able to have multiple and "push" then into the hash with a foreach statment. Is that posible?
RE (tilly) 1: Variable auto creation
by tilly (Archbishop) on Sep 28, 2000 at 14:14 UTC