in reply to Matching a KEY in a HASH

You want to match a key based on a substring? and print all values that match? You can use the Tie::Hash mentioned above or just to match a substring you can do...
for(keys %category) { print "$category{$_}\n" if /\Q$variable\E/i; }
the \Q \E makes sure that you match the characters in $variable the way they are, (other a \ could screw you all up, or a . or a *, etc) and the i at the end makes it case-insensitive (often good in substring matching). Does that help?
                - Ant

Replies are listed 'Best First'.
Re: Re: Matching a KEY in a HASH
by SysAdm (Novice) on May 14, 2001 at 21:44 UTC
    Here's the code I'm currently using:
    %category = ( Anim => 'Animation Projects', Build => 'Building/Structural Projects', CAD => 'CAD/CAM Engineering Projects', ); my $value; $value = (sort values %category); print "$value" if (exists($category{"$form{'USER_INPUT'}"})) ;

    It prints EVERY $value instead of just the $value for the matching $form{'USER_INPUT'}.

    I hope my question is now clearer and makes more sense..
      Yes, stop getting all the values, when all you want is one value. Use the code I've posted twice in this thread, as have others.

      -- Randal L. Schwartz, Perl hacker

      Ummm, first things first...
      $value = (sort values %category);
      will store the last value of the sorted list of values in $value, this is most likely not what you want. You are looking to print the value of %category that the key matches $form{'USER_INPUT'}? then use..
      print $category{$form{'USER_INPUT'} if $category{$form{'USER_INPUT'};
      do you just want the value of Anim if the user inputs Anim, or do you want Build AND CAD when the user inputs 'd'?
                      - Ant

      As merlyn said, looks like you are trying to grab all the 'values' with the $value = (sort values %category); statement.

      If you just use

      print "$category{$form{'USER_INPUT'}}" if exists $category{$form{'USER_INPUT'}};

      everything should work fine. (At least it did for me... :)

      D a d d i o

        Thanks!
        for everyone's help on this....

        It works great now...!

        _________SysAdm