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

trenchwar++ for identifying as homework.

You should use eq to test for string equality (use == only when comparing numbers). See perlop for other string and numeric comparison operators.

If you want to match partial city names instead of whole city names, you might be interested in substr and length or perhaps index. If you want to be case insensitive as well, lc could help.

If you want LA to be a special case, check for it before you check for anything else.

if ( $input_city eq 'Los Angeles' ) { # handle the City of Angels } else { # handle cities of non-angels }

Replies are listed 'Best First'.
Re^2: **HomeWork** Trying to search an array and match it to a user input
by trenchwar (Beadle) on Apr 01, 2008 at 03:04 UTC
    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"; } } }

      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.