Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2003
    Location
    san jose, CA
    Posts
    68

    Unanswered: compare user input with Array index?

    Dear forum members:

    I have this programming assignment from school. One requirement is,

    "Asks the user for the index (movie array index) of a movie to delete from the list. If the user enters invalid input, tell the user and prompt him again for a valid index. If the input is valid, delete that movie from the list."

    I used <STDIN> function to get use input, but I have trouble to fingure out how to use a loop structure to compare user input (should be a integer) with array index.

    My code segment are like this:

    foreach my $index (0 .. $#movies)
    {

    while( ($input < $index) || ( $input > $index) )
    {

    print "Invalid array_index, please enter another one: ";
    $input = <STDIN>;
    }

    }

    I foud out this won't work, because user's input is random and it won't match exact index (assigned by foreach loop).

    I think a while loop should do the trick, but what's the condition should be in while loop? Could someone give me some suggestions or hints. I appreciate your hlep!

    Jeff
    11-07-04

  2. #2
    Join Date
    Jan 2004
    Location
    Germany
    Posts
    167
    Test this code:
    Code:
    #! /usr/bin/perl
    
    use strict;
    use warnings;
    
    my @movies = ('Bruce Almighty', 'Save the last dance', '10 things I hate about you');
    my $input;
    
    while(1){
      print "Please enter the index of the movie you want to delete: ";
      $input = <STDIN>;
      chomp $input;
      last if($input !~ /\D/ && $input > 0 && $input < $#movies); 
      # test, whether $input is an integer and within the index range
    }
    
    # delete from array
    board.perl-community.de - The German Perl-Community

  3. #3
    Join Date
    Aug 2003
    Location
    san jose, CA
    Posts
    68

    Thanks for you help!

    Hello Renne:

    Thanks for your help, I studied your code and figured out my own solution for this problem. I appreciate your help, have a great day.

    Jeff
    11-08-04

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •