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

Hey Monks
I have an array with values, a hash with info on those values and a variable.
What I need is a piece of code that will cycle through the array to see if something matches the variable. If it does its info gets added to the @result_array and if not the variable itself gets added to the @result_array.
So if the variable was var1 as below the @result_array would contain "info1" however if the variable was something like var67 the @result_array would contain "var67".
my %hash ={"var1", "info1", "var2", "info2", "var3", "info3"}; my @array=("var1","var2","var3"); my $where = "var1"; my $used = 0; foreach my $item(@array){ if ($item eq $where) { push @result_array, $hash{$item}; $used = 1; } } unless ($used = 1){ push @result_array, $where; } $used = 0;

Thanks everybody

j o h n i r l .

Sum day soon I'Il lern how 2 spelI (nad tYpe)

Replies are listed 'Best First'.
Re: Variable Selection
by tommyw (Hermit) on Aug 30, 2002 at 10:06 UTC

    The absolute simplest fix to your code would be to initialise the hash correctly; round brackets not curly:

    my %hash =("var1", "info1", "var2", "info2", "var3", "info3");
    , and you've broken the equality test in your unless clause: ==, not =.

    The perlish rewrite of your code would be:

    if (grep {$_ eq $where} @array) { push @result_array, $hash{$where}; } else { push @result_array, $where; }

    Update: Of course, if the array is simply the keys of the hash, it gets even easier:

    push @result_array, $hash{$where} || $where;

    --
    Tommy
    Too stupid to live.
    Too stubborn to die.

Re: Variable Selection
by fruiture (Curate) on Aug 30, 2002 at 10:04 UTC

    Check perldata why your hash initialization is broken. check perlsyn for last. Check perlop for the meaning of '=' and '==' and then think of totally leaving the @array out of your code and directly looking for $where in the %hash, via exists. HTH

    --
    http://fruiture.de
Re: Variable Selection
by Preceptor (Deacon) on Aug 30, 2002 at 10:04 UTC
    how about:
    foreach my $item ( @array ) { if ( $item eq $where ) { push ( @result_array, ( $hash{$item} ) ? $hash{$item} : $item ); } }