Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

The command line arguments

by abcdefg (Acolyte)
on Apr 04, 2012 at 15:59 UTC ( [id://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
    Getopt::Long
    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:

    $ script.pl -p prod -i foo -h bar i

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-19 19:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found