Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

The command line arguments

by abcdefg (Acolyte)
on Apr 04, 2012 at 15:59 UTC ( #963470=perlquestion: print w/replies, xml ) Need Help??

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

Hi All, I am trying to add "OR" option in command line args to my perl script.I did used command line like

Usage: $scriptname (-p <product_type> -i <input_filename> -o <output_f +ilename> )

Now I want user to have the option of either giving -i <input_filename> or -h <image_filename>. How can I do that?? I tried doing following which definitely didnt work.

Usage: $scriptname (-p <product_type> -i <input_filename>|| -h<image_f +ilename> -o <output_filename> )

Also after giving this option how can I use if else for command line. I mean if user give option -i<input_filename> do this else if user give -h<image_filename> do that???

Replies are listed 'Best First'.
Re: The command line arguments
by dasgar (Priest) on Apr 04, 2012 at 16:49 UTC

    I'm not sure what you "tried", but I think you're approaching the issue the wrong way.

    The way that I would approach the problem would be to use Getopt::Std or Getopt::Long to read in the options first. Then write code to handle the validation of the options. That's where you'll handle the "or" situation.

    The example code below illustrates what I'm suggesting. You'll probably want to add more validation and error trapping, but it will show how to handle the "or" logic of options that you're wanting to do.

    use strict; use warnings; use Getopt::Long; my $prod_type = ""; my $in_file = ""; my $out_file = ""; my $img_file = ""; my $valid = GetOptions( 'p=s' => \$prod_type, 'i=s' => \$in_file, 'o=s' => \$out_file, 'h=s' => \$img_file, ); if (($in_file eq "") and ($img_file eq "")) { my $msg = ""; die "Missing required option(s). The -i or -h option must be specifi +ed."; } if ($in_file ne "") { # do some stuff and ignore the -h flag } else { # do other stuff # earlier if statement guarantees that -h flag was used # i.e there was no -i flag used, but the -h flag was used }
Re: The command line arguments
by toolic (Bishop) on Apr 04, 2012 at 16:54 UTC
    use warnings; use strict; use Getopt::Long; my %opts; GetOptions(\%opts, qw( p=s o=s i=s h=s )) or die; if ($opts{i}) { print "i\n"; } elsif ($opts{h}) { print "h\n"; }

    Here is one invocation:

    $ -p prod -i foo -h bar i

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2023-03-31 16:36 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (76 votes). Check out past polls.