Pass argument through command line and popup if the user has not given the input
The code below creates a file and accepts an input argument through the command line.
I want to do two things:
If the user forgot to enter the input on the command line, the s开发者_如何学JAVAystem should give some sort of alert or message. Assume if I forgot to give an input argument, then the system should not proceed with the script execution.
Assume if the system tries to create the already existing file, at present we are managing with showing a message like "File already exists", but instead I want to ask something like "File already exists, are you sure you want to override? yes/no". If he answers yes, then simply override the existing one, else the system should ask for another input from the user.
#!/usr/local/bin/perl
#print "content-type: text/html \n\n"; #HTTP HEADER
$numArgs = $#ARGV + 1;
foreach $argnum (0 .. $#ARGV) {
$GET_ALL_USER_INPUTS = "$ARGV[$argnum]\n";
}
@INPUT_ARR = split(/,/, $GET_ALL_USER_INPUTS);
$filename = "DD_WRITE_${INPUT_ARR[0]}.txt";
$GET_ARR_SIZE = scalar @INPUT_ARR;
$CLIENT_NAME = "T-sys";
$DD_CONTENT = "Design Document ${INPUT_ARR[0]} - ${CLIENT_NAME} :-\n";
$DD_CONTENT .= "--------------------------------------";
#get the no length and generate dotted lines
for($i=0;$i<=length(${INPUT_ARR[0]});$i++){
$DD_CONTENT .= "-";
}
$DD_CONTENT .= "--------------\n";
$DD_CONTENT .= "Database Details\n";
if (-e "${filename}") {
print "File exists!";
exit;
}
else {
open(FILE, ">", "$filename") or die "Cannot open $filename - $!";
print FILE "${DD_CONTENT}\n";
close (FILE);
}
I understand the question to be "How do I prompt a user?" because you do not know how to do that. I skip part 1 of the problem description because you already do know about exit
.
First, you should replace your command-line argument handling with Getopt::Long. As it is written now, it is needlessly convoluted.
Getting input from a user at run-time is easy with ExtUtils::MakeMaker which already comes with the Perl distribution.
use ExtUtils::MakeMaker qw(prompt);
my $user_answer = prompt 'Okay to overwrite? ';
if ('y' eq $user_answer) { …
I see that you have commented out a piece of code about HTTP. If you intend to run this program under a CGI environment, prompting will not work as you would expect. On the Web, you need a different technology and control flow altogether.
The existence of a command line argument can be determined pretty easily:
if (exists $ARGV[0]) { do_stuff_with_args } else { die "No arguments!"; }
精彩评论