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

    Unanswered: How to exit the loop structure by catch "Enter Key" from command line?

    Hello everyone:

    I have this foreach loop which push movie titles into a existing array until user hit the 'Enter key'. I tested my code it won't stop taking input from command line when user hit the 'Enter key'. It will exit the loop structure when user press <Ctrl_Z> which is termination in windows.

    I post my code segment here, Could someone take a look at it and kindly points out what I had done wrong. I really struck here, I need some help!

    print "please enter movies you want to add to the list\n",
    "when finish hit the enter key on a separate line: \n";


    chomp(@added_movies = <STDIN>);

    print"\n\n";

    foreach my $movie_index(0 .. $#added_movies)
    {

    #If user hit the 'Enter key' exit foreach loop
    if( $added_movies[$movie_index] eq "")
    #if($added_movies[$movie_index] eq "\n") this one here won't work either
    {
    last;
    }

    #add new movie titles into existing movie list
    if(exists $added_movies[$movie_index] )
    {
    push (@movies, $added_movies[$movie_index] );
    }
    }

    print "Enter key pressed, entry finished. \n\n";

  2. #2
    Join Date
    Jun 2004
    Location
    Nowhere Near You
    Posts
    89
    There's nothing wrong with using the cntrl/z to terminate the input stream and you can do it more than once as will be done here ...
    Code:
    #!\users\bin\perl
    use strict;
    use warnings;
    # Load titles
    my(@Titles);
       {
      print "please enter movies you want to add to the list\n",
      "cntrl/Z to termnate: \n";
      chomp(@Titles=<STDIN>);
       };
    # Display titles for the user in alphabetic order
       {
      @Titles=sort @Titles;
      print "$_: $Titles[$_]\n" foreach (0..$#Titles);
       };
    # Delete the unwanted titles
       {
      print "number of the title to be deleted(cntrl/Z to termnate):";
      while (<STDIN>) {
        undef($Titles[$_]) if (defined $Titles[$_]);
        print "number of the title to be deleted(cntrl/Z to termnate):";
         };
       };
    # Display titles for the user in alphabetic order
       {
      print (defined $Titles[$_] ? "$_:$Titles[$_]\n" : "$_:\n") foreach (0..$#Titles);
       };
    Last edited by senza_nome; 11-11-04 at 11:18.

Posting Permissions

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