in reply to Stdin for just numbers.
Here's one way to structure things so that the coding is easier. (I'm just going with basic usage in this example - the module has various options and extra methods to make things easier for the person who is typing, such as keeping a history of responses, so they can be recalled and reused, etc. Notice that Term::ReadLine strips off the newline characters for you.)
(There are different "flavors" of Term::ReadLine that you can use; your perl version probably has a "default" version that will suit your needs.)#!/usr/bin/perl use strict; use warnings; use Term::ReadLine; my $term = Term::ReadLine->new(); my @prompts = ( "the starting amount", "your current age", "the age you want to retire", "amount deposited per year", "the annual interest rate", "expected retirement money" ); my %responses; for my $prompt ( @prompts ) { my $response = ''; until ( $response =~ /^\d+$/ ) { $response = $term->readline( "Enter $prompt: " ); last unless defined( $response ); if ( $response =~ /\D/ ) { warn "Numeric answers only, please. Try again.\n"; } elsif ( $prompt eq "the age you want to retire" and $response < $responses{"your current age"} ) { warn sprintf( "We can't change the past. Give me a number +> %d\n", $responses{"your current age"} ); $response = ""; } } $responses{$prompt} = $response if ( defined( $response )); } printf "\nThank you for your %d answers\n", scalar keys( %responses ); for ( @prompts ) { print " $_ : $responses{$_}\n" if ( exists( $responses{$_} )); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Stdin for just numbers.
by BillKSmith (Monsignor) on Mar 16, 2015 at 13:30 UTC | |
by AppleFritter (Vicar) on Mar 16, 2015 at 17:10 UTC | |
by davido (Cardinal) on Mar 16, 2015 at 20:02 UTC |