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

I am working the Llama (what else is new) and have a problem with my code (again what else..). This will eventually use STDIN as input but for now I am using an @. The sub is supposed to return only the values whose keys are named in the input along with the input which did not match any key. What I get is all the values every time, regardless of input.

I would really appreciate it if someone could get me thinking in the right direction without giving me corrected code, I really want to get this.
TIA
jg
#!/usr/local/bin/perl -w use strict; my @a=(9,8,1); my (@names,@name_nums); @names=name_nums(@a); print "@names"; sub name_nums { my (%list,@name_nums,$this_num); @list{1..9}=qw(one two three four five six seven eight nine); foreach $_ (keys (%list)){ if (exists $list{$_}){ $this_num = $list{$_}; push (@name_nums,$this_num); }else{ push (@name_nums,$_); } } return @name_nums; }
Ain't no time to hate! Barely time to wait! ~RH

Replies are listed 'Best First'.
Re: matching input to hash keys
by merlyn (Sage) on Sep 30, 2001 at 02:36 UTC
    foreach $_ (keys (%list)){ if (exists $list{$_}){
    While not trying to correct your code, I'll suggest that this expression always returns true. A key in a hash always exists in the hash!

    -- Randal L. Schwartz, Perl hacker

Re: matching input to hash keys
by Ovid (Cardinal) on Sep 30, 2001 at 02:09 UTC

    Well, you've defined the list you want in @a, passed it to the subroutine, but never used it :)

    Update: Ugh! I just saw your comment about not giving you corrected code, so I've put my fix in an HTML comment. "View source", if you dare!

    Cheers,
    Ovid

    Vote for paco!

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re: matching input to hash keys
by blakem (Monsignor) on Sep 30, 2001 at 02:12 UTC
    Looks like you are passing an array to name_nums(), but not doing anything with it... try replacing your foreach line in name_nums() with:
    foreach(@_) {
    I think that should get you pointed in the right direction.... ;-)

    -Blake