Re: Comparing an array with hash keys



On Sep 30, Mark Martin said:

I want to compare the elements of an array with the keys in a hash. If matches are found, I want to store the values associated with the matched keys in an array for future processing :

my @storage_array = ();
foreach $item(@original array) { if (exists $original_hash{$item}) {
push(@storage_array, ?????? )
}
}

Your ?????? should just be $original_hash{$item}, I expect, although this code could be written far more succinctly as a map():


  my @storage_array = map {
    exists $original_hash{$_} ? $original_hash{$_} : ()
  } @original_array;

--
Jeff "japhy" Pinyan        %  How can we ever be the sold short or
RPI Acacia Brother #734    %  the cheated, we who for every service
http://www.perlmonks.org/  %  have long ago been overpaid?
http://princeton.pm.org/   %    -- Meister Eckhart
.



Relevant Pages

  • Re: Stuffing @users into $self->{users}
    ... have an array called @users which is populated in sub new. ... foreach my $user ... I just want to be able to store ...
    (comp.lang.perl.misc)
  • Re: print a selection of a file
    ... foreach { ... I would not store the whole file into an array unless you really need this. ... print if $outputflag; ...
    (perl.beginners)
  • Re: Finding the nearest match without reusing results
    ... comparing an array with a value generates an array of Trues and ... Any diff with wrong State or with used Store is implicitly zeroed out. ... Each must be larger than the absolute value of the maximum Sales ... go.....it just needs to return the closest match. ...
    (microsoft.public.excel.programming)
  • Re: read keyboard input and storing in an array?
    ... > I'm trying to store user input in an array, ... You have the beginnings of that logic already since your prompt tells the ... 201st value since the array only has room for 200 values. ... This will force you to store the int values as Integer ('Integer' ...
    (comp.lang.java.help)
  • Re: [PHP] foreach() using current() strange beahvior
    ... that's expected as foreach moves the internal array pointer, ... When using the internal pointer just by calling current(so not moving ... Unless the array is referenced, foreach operates on a copy of the ...
    (php.general)