perl script command line option driven script

could someone show me a sample command line option driven script?

i want to see an easy way to write one and how i can execute it using command line options such as typing in

read.pl -i <id> -c <cmds> -s <start> -e <end>

would read out all the commands run by ID . from start time to end time.

$
$ cat perl_getopt
#! /usr/bin/perl -w
use Getopt::Std;

our($opt_c, $opt_s, $opt_e);
getopt('c:s:e:');

if (defined($opt_c)) {print "option c is $opt_c \n";}
if (defined($opt_s)) {print "option s is $opt_s \n";}
if (defined($opt_e)) {print "option e is $opt_e \n";}

foreach $arg (@ARGV) { print "arg = $arg\n"; }
$
$
$
$
$ ./perl_getopt -s sval  -c cval   one two 333 fore
option c is cval
option s is sval
arg = one
arg = two
arg = 333
arg = fore
$
1 Like

Hi.

Also:

-s enables rudimentary switch parsing for switches on the command
line after the program name but before any filename arguments (or
before an argument of --). Any switch found there is removed from
@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" }

-- excerpt from man perlrun , q.v.

So, for a file p1:

#!/usr/bin/perl -s
if ($xyz) { print "$xyz\n" }

Running as directed, produces:

% ./p1 -xyz="Hello, world."
Hello, world.

My current preference is to use Getopt::Euclid because it generates a man page and a command line parser. I would not call it easy, so Getopt::Std is preferable from that respect. The option -s is probably the easiest, but the man page should be read carefully ... cheers, drl

1 Like

thank you for your reply.

excuse me but why are there $ in all the lines?

That's how you indicate a scalar variable. You can't be very far into Perl if you are not acquanted with that use of the dollar sign. You may want to download the Perl tutorial from here: Featured Books and Articles by Active Forum Members - Links

Sorry, I should have been more clear.

I know the $ indicates that it is a scalar variable but i have never seen $ by itself on a line.

I know that $opt_c is a variable and i know what $_ does but what does $ do by itself on it's own line.

Oh. That is called a "prompt". The shell displays it to indicate that I can type something.

Ahh i see, sorry for the confusion.

Got a quesiton

when i copy that code and run it

./perl_getopt -s sval  -c cval   one two 333 fore

my output is not

option c is cval
option s is sval
arg = one
arg = two
arg = 333
arg = fore

instead i get

arg - sval
arg = -c
arg = cval
arg = one
arg = two
arg = 333
arg = fore

is there a specific reason for this?

---------- Post updated at 03:59 PM ---------- Previous update was at 03:58 PM ----------

NVM i figured it out. :slight_smile: stupid meeeee THANKS