Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

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

by trenchwar (Beadle)
on Mar 27, 2008 at 16:23 UTC ( #676780=perlquestion: print w/replies, xml ) Need Help??

trenchwar has asked for the wisdom of the Perl Monks concerning the following question:

Hello Hello Monks!
Identified as homework! I am sure I am just not putting my mind into this, but I understand the logic, just not how to get there.
Basically, I have the list of cities, and want the user to enter a city of their choice, LA is there but I wanted it to spit back (LA is not an option).
On top of that be able to take their input (be it one letter or the entire name) and match it to the array and print the results.
I hope this makes some sense, any help or guidance would be greatly appreciated.
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:(Baltimore Chicago Los Angeles New + York San Diego)\n"; chomp (my $input_city = <STDIN> ); foreach $city (@myCities) { if ( $input_city == $myCities ) { #exists; } else { print "I'm sorry,we no longer tour LA, please t +ry again.\n"; } }
  • Comment on **HomeWork** Trying to search an array and match it to a user input
  • Download Code

Replies are listed 'Best First'.
Re: **HomeWork** Trying to search an array and match it to a user input
by TGI (Parson) on Mar 27, 2008 at 16:36 UTC

    Try using grep to narrow your list.

    You'll also want to look at perlre and perlreref.

    Thank you for identifying this post as homework. You could have just posted without identifying your question and fished for a complete answer. Instead, you showed that you value your education enough to work at it.


    TGI says moo

      perlre is what I was looking for! Thanks you!
Re: **HomeWork** Trying to search an array and match it to a user input
by Fletch (Chancellor) on Mar 27, 2008 at 16:35 UTC

    Hint: == is for numbers; eq is for strings. See perlop and read about comparison operators.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: **HomeWork** Trying to search an array and match it to a user input
by kyle (Abbot) on Mar 27, 2008 at 16:38 UTC

    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 }
      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.

Re: **HomeWork** Trying to search an array and match it to a user input
by NetWallah (Canon) on Mar 27, 2008 at 17:43 UTC
    A few more points:
    • Comparing $input_city with $myCities will always fail (Unless someone typed the entire city list). You probably intended to compare with $city
    • With your current code, every failed comparison will print the "I'm sorry" message. That should only print if ALL comparisons fail (as in after the for loop.)
    • As pointed out earlier, "==" is for numeric comparison. Try "eq".
    • The uc and lc functions can be used to make the comparisons case insensitive (or you could use a regular expression).
    If you have studied hashes, using that construct would make your code considerably simpler, and easier to read.

    Good luck.

         "As you get older three things happen. The first is your memory goes, and I can't remember the other two... " - Sir Norman Wisdom

      You can also take a look at the module Text::Abbrev. It makes it easy to work with abbreviations of strings.
      %hash = abbrev (split(':', "Baltimore:Chicago:Los Angeles:New York:San Diego:"));
      chomp (my $input_city = <STDIN> );
      if (exists $hash{$input_city}) { ...... }
      
Re: **HomeWork** Trying to search an array and match it to a user input
by starbolin (Hermit) on Mar 27, 2008 at 18:23 UTC

    You've done well so far. You'll need two if{} statements inside your loop though. One to check if there is a match and one to warn when the user has chosen LA.

    Your if statement should check against the loop variable $city instead of your global $myCities.

    Normally for lookups I prefer to store the items in a hash. Then you don't need a loop. You just say something like "if ( exists $hash-of-cities{ $input_city }){do-something}". To handle partial inputs you store only the first three letters of the city and match those against the first three letters of the user's input.

    A nice bonus add-in would be to store both the city name and it's abbreviation in the hash like this: %cities=( 'New'=>'1', 'NY'=>"1", .... ); then doing a hash lookup with either input will be successful.

    Good luck. Keep at it!


    s//----->\t/;$~="JAPH";s//\r<$~~/;{s|~$~-|-~$~|||s |-$~~|$~~-|||s,<$~~,<~$~,,s,~$~>,$~~>,, $|=1,select$,,$,,$,,1e-1;print;redo}
Re: **HomeWork** Trying to search an array and match it to a user input
by apl (Monsignor) on Mar 27, 2008 at 16:55 UTC
    Minor suggestion: change the prompt of your program to:
    print "Please pick one of the following cities by entering any portion + of the beginning of the city name:($myCities)\n";

    That way, your prompt always reflects what your program considers a list of valiid responses.

Re: **HomeWork** Trying to search an array and match it to a user input
by nedals (Deacon) on Mar 28, 2008 at 00:29 UTC
    Some additional thoughts...
    # Since you are pre-defining the cities, you don't really need the spl +it. # Simply pre-populate an array 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:(Baltimore Chicago Los Angeles New York San Diego)\n"; # Use the above array to populate the names. That way you don't have t +o do it twice. chomp (my $input_city = <STDIN> ); # Take a look at 'for' and '$_' for the loop foreach $city (@myCities) { # As has been noted, use 'eq' (strings) instead of '==' (numbers) # Better still, use a regular expression to be able to match 1 or +more letters # and, if all you want is the print output, take a look at 'unless +' if ( $input_city == $myCities ) { #exists; } else { print "I'm sorry,we no longer tour LA, please try again.\n"; } }
Re: **HomeWork** Trying to search an array and match it to a user input
by swampyankee (Parson) on Mar 28, 2008 at 15:27 UTC

    I, too, would suggest using grep, and reading the perlre and perlretut. I would also suggest that you make sure that your comparisons are case-insensitive, which can be done by adding the "i" flag to a regex or by using uc or lc on both sides of the string equality test, eq.

    There is a number of alternatives to using an array, such as a dispatch tables, but I think they're overkill for this particular case.


    emc

    Information about American English usage here and here. Floating point issues? Please read this before posting.

Re: **HomeWork** Trying to search an array and match it to a user input
by Anonymous Monk on Mar 28, 2008 at 04:12 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://676780]
Approved by kyle
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2021-10-16 03:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (69 votes). Check out past polls.

    Notices?