#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;

my %opts = (); # save all cmd line opions in this hash
GetOptions ( # read cmd line args
    \%opts,
    "name=s", # provide name on cmd line with '--name "Tom"'
    "age=i", # provide age on cmd line with '--age 42'
);

# ask user or get values from cmd line
my $name = askName(\%opts);
$name = askName(\%opts); # prove that the same question is not asked twice
my $age = askAge(\%opts);

# "main"
print "Hi $name!\n";
print "You are $age years old.\n";
exit(0)


sub ask {
    # helper function to either access cmd line parameters or ask user if
    # needed
    my ($opts, $key, $prompt, $default) = @_;
    my $value = $opts->{$key};
    if (!defined($value)) { # not specified on cmd line
        $default = "" if (!defined($default)); # not default value provided
        print "$prompt [default: $default]:\n";
        $value = <STDIN>; # read user input
        chomp($value); # trim
        if ($value eq "") {
            $value = $default; # overwrite with default
        }
        $opts->{$key} = $value; # store provided value for future reference
    } else {
        # provided on cmd line
    }
    return $value;
}

sub askName {
    my ($opts) = @_;
    return ask($opts, "name", "Please enter your name", "Tom");
}

sub askAge {
    my ($opts) = @_;
    return ask($opts, "age", "Please enter your age", "42");
}
