in reply to Search Hash with array element Help!

- For every array element, - Extract the numeric component of the element. - If the hash contains a key matching the extracted component, - If the hash value is empty, - Print whatever - Else - Print whatever

Update: I was letting you do the work yourself, but since others have posted code,

for my $id (@array_code) { my ($num) = $id =~ /(\d+)/ or next; next if !exists($code_numbers{$num}); my $code = $code_numbers{$num} || 'IN'; print("$id $code\n"); }

Or if %code_numbers can contain a value of '0',

for my $id (@array_code) { my ($num) = $id =~ /(\d+)/ or next; next if !exists($code_numbers{$num}); my $code = $code_numbers{$num}; $code = 'IN' if !length($code); print("$id $code\n"); }

Replies are listed 'Best First'.
Re^2: Search Hash with array element Help!
by snape (Pilgrim) on Mar 04, 2010 at 21:38 UTC

    I really liked ur concise code. :) I didn't understand how the following statement:

    my ($num) = $id =~ /(\d+)/ or next;

    I understand what the result is but I didn't understand how does that gives you a numeric form and removes the characters. Actually, this is the first time I have seen something like this therefore, can you please forward me some reference material too.

    Thanks.

      The same with parens that illustrate precedence:
      ( my ($num) = ( $id =~ /(\d+)/ ) ) or next;

      The first thing that happens is that $id is matched against /(\d+)/.

      If it matches, a list of all the captured data (that which the content of parens in the pattern matched) is returned by the match operator. The first (and only) element of that list is assigned to $num. The assignment returns 1 (the size of the list returned by the match), so next is skipped.

      If it doesn't matches, an empty list is returned. undef is assigned to $num (which won't be used). The assignment returns zero (the size of the list returned by the match), so next is evaluated and the rest of the loop is skipped.

      All of these operators (match, list assignment and or) are documented in perlop.