perl flags

Posted on 2009-04-20
Last Modified: 2013-12-26
How can I make my script understand flags?
as in

perl --flag1=0 --flag2=0

I would like to use flags instead of simple arguments because each of my arguments have defaults and if the user only wants to specify flag2, I don't want to force him/her to have to specify flag1 too as the default should be used.
Question by:NewtonianB
    LVL 84

    Assisted Solution

    LVL 1

    Accepted Solution

    use Getopt::Long;
    use Getopt::Long;
    GetOptions      (
                    "flag1=s" => \$myFlag1,
                    "flag2=s"  => \$myFlag2,
                    "help"    => \$myHelp
    if (defined $myHelp) {  displayHelpDialog; }
    do { print "\nERROR: You must provide FLAG1 using the --flag1 option\n Use --help for usage info.\nProcess died"; exit(12); } unless defined $myFlag1;
    do { print "\nERROR: You must provide FLAG2 using the --flag2 option\n Use --help for usage info.\nProcess died"; exit(12); } unless defined $myFlag2;

    Open in new window

    LVL 39

    Assisted Solution


    use Getopt::Long;
    my $flag1=1;  #Default for flag1
    my $flag2=2;  #Default for flag2
        "flag1=i" => \$flag1,
        "flag2=i" => \$flag2,
        ) or die "Could not process options\n";

    Open in new window


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Highfive Gives IT Their Time Back

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Suggested Solutions

    Introduction: The undo support, implementing a stack. Continuing from the eigth article about sudoku.   We need a mechanism to keep track of the digits entered so as to implement an undo mechanism.  This should be a ‘Last In First Out’ collec…
    A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (,  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

    758 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now