Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

defining variable values on the commandline

by fjonckers (Novice)
on Jul 09, 2002 at 15:33 UTC ( #180513=perlquestion: print w/replies, xml ) Need Help??

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

I remember seeing this somewhere but can't find it anymore....

want to define the value of a var on the commandline. is this possible ?

example commandline: perl -e $myvar=123;

example perl script print "the value is $myvar";

this is a very simple example of course...

probably a stupid syntax error somewhere ;-)

any help greatly appreciated!


Edited: ~Tue Jul 9 18:24:02 2002 (GMT), by footpad:
Added <code> (and other formatting) tags, per Consideration.

Replies are listed 'Best First'.
•Re: defining variable values on the commandline
by merlyn (Sage) on Jul 09, 2002 at 15:44 UTC
    perldoc perlrun:
    -s enables rudimentary switch parsing for switches on the comman +d line after the program name but before any filename arguments (or +before an argument of --). This means you can have switches with two leading dashes (--help). Any switch found there is removed fr +om @ARGV and sets the corresponding variable in the Perl program +. The following program prints "1" if the program is invoked with a + -xyz switch, and "abc" if it is invoked with -xyz=abc. #!/usr/bin/perl -s if ($xyz) { print "$xyz\n" } Do note that --help creates the variable ${-help}, which is n +ot compliant with "strict refs".
    And that last note is noteworthy. Such variables are not the same as lexical variables; they are package variables in package main::.

    -- Randal L. Schwartz, Perl hacker

Re: defining variable values on the commandline
by broquaint (Abbot) on Jul 09, 2002 at 15:45 UTC
    want to define the value of a var on the commandline is this possible ?
    It certainly is. See the -s option in the perlrun manpage. Here's a brief example
    shell> cat > print "\$foo is $foo\n"; ^D shell> perl -s -foo="a string" $foo is a string



      just what the monkdoctor ordered ... the -s works fine Thanks Guys !
Re: defining variable values on the commandline
by Fastolfe (Vicar) on Jul 09, 2002 at 21:08 UTC
    When dealing with anything but one-liners, I might also suggest you examine the Getopt:: line of modules (like Getopt::Std). These generally provide a more flexible mechanism for grabbing command-line arguments, and frequently can make use of a hash to avoid polluting your global name space.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://180513]
Approved by broquaint
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2021-03-06 14:53 GMT
Find Nodes?
    Voting Booth?
    My favorite kind of desktop background is:

    Results (116 votes). Check out past polls.