use IO::Prompt::Hooked; my $file = prompt ( message => 'Enter your filename ("A" to abort):', tries => 10, validate => sub { -e -f shift }, escape => sub { shift =~ /^A$/ && die "Aborting." }, error => sub { die "Excessive tries; Aborting." unless $_[1]; return "[$_[0]]: Invalid filename. Please re-enter.\n\n" }, ); print "\n*** You chose '$file'. ***\n";

This solution offers the user ten attempts at producing a valid filename, and then dies if one isn't obtained. The user may also escape early by entering "A" to abort, in which case this also been coded to die.

On each attempt, the input is checked to see if it exists in the current working directory, and if it's a file. If this validation passes, the filename is printed. If not, we print a message and prompt again.

IO::Prompt::Hooked is used here, but if you want to build your own logic from scratch, IO::Prompt::Tiny would be a good choice.

If this is homework then you're probably required, instead, to prompt using the <STDIN> (diamond) operator, and do all your own validation and looping logic. But at least you might be able to get some ideas from this.


Dave


In reply to Re: taking file from user by davido
in thread taking file from user by shushant

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.