I don't want to start any "style wars". But my natural inclination would have been to code
prompt_read() something like this:
sub prompt_read
{
my $prompt = shift;
print $prompt;
my $response = <STDIN>;
$response =~ s/^\s*|\s*$//g;
return $response;
}
Note: these "standard idioms" can be used, but with
recent Perl's the more complex regex above is slightly faster.
$response =~ s/^\s*//; # these 2 statements do the same
$response =~ s/\s*$//; # but slightly slower
Some Comments:
- I prefer the bracketing style shown for Perl. For Java I like the more compact form because of all of the little "getter and setter" subs which can take up a lot of space.
- In Perl, I look for the first line of the sub to understand the input args. Perl doesn't have prototypes like C but this appears to work just fine.
- Giving a name to a variable is "cheap", "very cheap" in terms of execution speed. I assigned $prompt as the sub's input value. There is nothing "un-Perl" about that at all. Likewise making a new variable $response for the input is "very cheap". I don't assign values to $_ which I consider to "belong to Perl". In for() or foreach() loops I assign my own name for the loop variable rather than $_. This prevents problems in nested foreach() loops as well as providing some more documentation, provided of course that the loop variable name makes sense!
- idiomatic Perl shows up in the next line. In Python, you have to explicitly import stuff to use regex and then explicitly compile the regex, then use it in another statement. In Perl, regex is "built-into the language". Normal CLI input conventions would be to strip all leading and trailing spaces as well as the line ending. That one statement does both. In a loop, Perl will take care of compiling the regex and not doing that step more than necessary (in most cases).
It would take a more complex example for the power of Perl vs Python to be demonstrable.
One point that I have is that well-written idiomatic Perl does not have to be cryptic.
I don't claim that my style above is better than other styles. This is just one example.
From a coding standpoint, I did like the idea of splitting out the function of sending a prompt and getting a response. I wrote a more sophisticated version of this awhile back. My expanded routine took a prompt,regex,err_message as input. This handled blank lines, did retries and such things.