Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #233 Read a command line string flag

Print the value of the flag -country passed to the program command line, or the default value "Canada" if no such flag was passed.

uses CustApp;
S := Application.GetOptionValue('country');
if S = '' then S := 'Canada';
writeln('Country = ',S);
#include <cstring>
#include <string>
int main(int argc, char** argv) {
    using namespace std;
    string s;
    char* x;
    while (x = *argv++)
        if (not strcmp(x, "-country"))
            if (x = *argv) {
                s = x;
                break;
            }
    if (s.empty()) s = "Canada";
    printf("%s", s.data());
}
import "flag"
var country = flag.String("country", "Canada", "user home country")
flag.Parse()
fmt.Println("country is", *country)
import static java.lang.System.out;
import static java.util.List.of;
import java.util.List;
public static void main(String[] args) {
    List<String> a = of(args);
    String s;
    int i = a.indexOf("-country"),
        n = a.size();
    if (i != -1 && ++i < n) s = a.get(i);
    else s = "Canada";
    out.println(s);
}
use Getopt::Long;
my $country = 'Canada';
GetOptions("country=s" => \$country) or die("Error in command line args\n");
print "Country is $country\n";
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-country', default='Canada', dest='country')
args = parser.parse_args()
print('country is', args.country)
from sys import argv
try:
    i = argv.index('-country')
    print(argv[i + 1])
except:
    print('Canada')

New implementation...
< >
programming-idioms.org