If you really want to go with this sort of "extended dialog" via stdin, you should check out Term::ReadLine.

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.)

#!/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{$_} )); }
(There are different "flavors" of Term::ReadLine that you can use; your perl version probably has a "default" version that will suit your needs.)

In reply to Re: Stdin for just numbers. by graff
in thread Stdin for just numbers. by programmercarlito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.