http://www.perlmonks.org?node_id=397520


in reply to String/Numeric Manipulation

Here's an alternative idea to simplify your code: instead of making the user type "q" to quit, they could either use "^C" to halt execution when they're done, or use the appropriate "eof" control character ("^Z" on windows, "^D" on unix), which will cause perl to "close" STDIN.

With that, the basic structure of the application could be done like this -- and I'll add an "extra feature":

use strict; $| = 1; # turn off output buffering if ( @ARGV and $ARGV[0] =~ /^\d+$/ and ! -f $ARGV[0] ) { show_sec( @ARGV ); } else { while (<>) # read a line from STDIN (or from a named file) { chomp; show_sec( $_ ); } } sub show_sec { for ( @_ ) { if (/^\d+$/) { my $sec = $_ * 86400; my $s = ( $_ == 1 ) ? '':'s'; print "[$_] day$s = [$sec] seconds\n"; } else { warn "$_ is not a positive integer; I'll ignore that.\n"; } } }
Let's suppose I call this script "d2s" (for "days to seconds"). If it's written like that, I can use it in any of the following ways:

In all cases, each input string is always handled the same way: if it is a positive integer it is converted to seconds, otherwise it is ignored, with a message that says so. (0 days is converted to 0 seconds, which seems okay to me.)

The  while (<>) loop provides all that flexibility. Also, when you use "warn" instead of "print" to deliver error messages about unusable input, those messages go to STDERR, so you can then redirect valid output (i.e. STDOUT) to a file to save the results for later re-use (e.g. "d2s > my_d2s.txt") -- there are many reasons for having the "good output" and "bad output" going to different file handles.

(Special note: the way @ARGV is handled there, if you have a data file called "12345" and give that name as the first arg, the script will read from that file, rather than using "12345" as a number to be converted. Basically, if the first arg is a number and is not a file, then all args are expected to be numbers to convert, otherwise they're all treated as files to be read.)