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{$_} )); }
In reply to Re: Stdin for just numbers.
by graff
in thread Stdin for just numbers.
by programmercarlito
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |