But I am reading from a file - no need to prompt (Perl)
Archive - Originally posted on "The Horse's Mouth" - 2009-09-14 18:27:33 - Graham Ellis
If you're writing a script that calls for user input, you had better prompt the user ... otherwise, the terminal / window will appear to hang and the user won't know what's going on. However - if you're reading your answers from a pre-prepared file or piping them in from another process, all of these immediately answered prompts will look really odd on the output.
In perl, you can use the -t file test, but on a file handle to see if that file handle is connected to an interactive device, or is not interactive. Most commonly, it's used on STDIN. Here's a demo program:
# See if we are using an interactive input ...
# If we are, prompt the user. If not, just read
if (-t STDIN) {
print "How much? "; }
chop($value = <STDIN>);
print "You paid $value too much\n";
Samples of this running, interactive with the prompt:
Dorothy-2:perl grahamellis$ perl sinter
How much? 33
You paid 33 too much
Dorothy-2:perl grahamellis$
And non-interactive:
Dorothy-2:perl grahamellis$ echo 55 | perl sinter
You paid 55 too much
Dorothy-2:perl grahamellis$
Illustration - A delegate uses one of our machines during a practical session on a Perl training course.