in reply to Re: **HomeWork** Trying to search an array and match it to a user input
in thread **HomeWork** Trying to search an array and match it to a user input

One more quick question....hopefully.
I think I figured out the first part (trying to say LA is not a choice)
But I want anything else in the array to be a successful choice and then exit the loop. I have tried a few things, but can't seem to get it to exit.
my $myCities = "Baltimore:Chicago:Los Angeles:New York:San Diego:"; my @myCities = split(':', $myCities); print "Please pick one of the following cities by entering any portion + of the beginning of the city name:(@myCities)\n"; while ( my $input_city = <STDIN> ){ foreach ($input_city) { if ($input_city =~ m/^L/i ) { print "We no longer tour LA, please try again!\n"; } if ( $input_city eq $myCities ){ ### here is where im lost## print "Found\n"; } } }
  • Comment on Re^2: **HomeWork** Trying to search an array and match it to a user input
  • Download Code

Replies are listed 'Best First'.
Re^3: **HomeWork** Trying to search an array and match it to a user input
by kyle (Abbot) on Apr 01, 2008 at 04:27 UTC

    Your foreach loop will loop over only one element, $input_city. What you want to do is loop over everything in @myCities. The syntax looks like this:

    foreach my $city ( @myCities ) { # $city is 'Baltimore' the fist time # $city is 'Chicago' the second time # etc. }

    You can see this in action with an example like this:

    foreach my $city ( @myCities ) { print "\$city = '$city'\n"; }

    A simple print (or warn) like that can be very helpful when debugging.

    What you could do is create a variable to hold the city that's found. This variable should start with a known bogus value (such as the empty string). Then loop through your cities and see if any one of them matches the $input_city. If there is a match, set the found city variable to the matching city. After the loop, check if the bogus value is still there or if some city was found. If a city was found, check if it's Los Angeles, and handle it accordingly.