in reply to Re: Compare two arrays
in thread Compare two arrays

Why can't this work?
... for my $filename (@file) { next unless $filename =~ /^\d+/; if(grep { %seen{$_} =~ $filename} keys %seen) { print " $filename\n"; } else { print "$filename is not in array\n"; } }

Replies are listed 'Best First'.
Re^3: Compare two arrays
by Eily (Monsignor) on Oct 01, 2014 at 17:25 UTC

    %seen{$_} is incorrect, you're only accessing one element (ie: a scalar) so you have to use the sigil $: $seen{$_}

    Now, look at your dump of \%test, you'll see that the value in $seen{$_} is actually an array, not a string, unless you have changed your data structure since the first post.

    Now your grep test (if I ignore your previous errors), applied to 96329XY and 96329XY_K.txt would turn into : "96329XY" =~ /96329XY_K.txt/, you probably have the wrong order. And you probably want to use quotemeta: grep { $filename =~ /\Q$_/ } keys %seen.

      I tested like this:
      ... for my $filename (@file) { #next unless $filename =~ /^\d+/; #if(grep { $seen{$_} =~ $filename} keys %seen) { # Failed #if(grep { $filename =~ $seen{$_} } keys %seen) { # Failed if(grep { $filename =~ /\Q$_/ } keys %seen) { print " YES - $filename\n"; } else { print " NO - $filename\n"; } }
      Why would it only work using "quotemeta"? I even removed the
      "next unless $filename =~ /^\d+/;

      Thanks for you time!

        quotemeta (the \Q in the regex) makes sure that perl tries to find the string exactly as it is in $filename. If you don't use it, it will "translate" any meta character into its regex meaning. In your case, it probably does the same though.