in reply to multiple matching in arrays
If I understand what you're trying to accomplish, I think you want something like this:
Several points you should take note of:#!/usr/bin/perl -w + use strict; use warnings; + my @array1 = ( "test", "test2", "test2", "test3", "test4", "test4" ); my @array2 = ( "test", "test", "test2.1", "test4.1", "test4.2", "test4 +.3" ); + my @save; + foreach my $item1 (@array1) { foreach my $item2 (@array2) { next unless defined $item2; if (match_names($item1, $item2)) { push (@save, $item1); $item2 = undef; last; } } } + printf "Results: save = %s\n", join(',', @save); sub match_names { # i have this part, its just a simple regex # something like: my ($x,$y) = @_; return 1 if ($y =~ /$x/); return 0; }
1. You really should use strict and warnings. They will help you catch so many errors and potential errors that you'd miss otherwise.
2. I converted array1 and array2 from array references to simple arrays. If you do this assignment:
my @array1 = [ "A", "B", "C" ];
you end up with an array containing a single value, which itself is a reference to an array. For example:
use strict; use warnings; + use Data::Dumper; + my @array1 = [ "test", "test2", "test2", "test3", "test4", "test4" ]; printf "Contents of 'array1' => %s\n", Dumper(\@array1); + my @array2 = ( "test", "test2", "test2", "test3", "test4", "test4" ); printf "Contents of 'array2' => %s\n", Dumper(\@array2); # Output will be as follows ... Contents of 'array1' => $VAR1 = [ [ 'test', 'test2', 'test2', 'test3', 'test4', 'test4' ] ]; Contents of 'array2' => $VAR1 = [ 'test', 'test2', 'test2', 'test3', 'test4', 'test4' ];
3. Your logic in match_names was backwards; what you wanted (at least if one goes by your example output) was:
return 1 if ($y =~ /$x/); # Swapped $x and $y
4. In match_names, you should really explicitly return a zero if the regex test fails. Also, you had a typo on the argument assignment (missing ')' when you assigned to "@_").
5. The code I presented works by deleting each found item from the second array so it won't be available as a "match" the next time. If you need to preserve your array2, you should make a copy instead:
my @array2_copy = @array2; foreach my $item1 (@array1) { foreach my $item2 (@array2_copy) { ... } }
Is that the solution you were looking for?
|
|---|