Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Nested foreach problem

by olus (Curate)
on Aug 19, 2008 at 17:16 UTC ( #705275=note: print w/ replies, xml ) Need Help??


in reply to Nested foreach problem

You don't seem to have problem 1 in your code. As for problem 2, if a name matches in several places, all occurrences will be printed. If you want uniqueness use an hash. The following example illustrates the differences:

use strict; use warnings; my @names = ('joe', 'mary', 'francis'); my @lines = <DATA>; my %lines_matched; my @all_found; foreach my $name (@names) { my $wanted = $name; foreach my $line (@lines) { if ($line =~ m/\b$wanted\b/i) { push @all_found, $line; $lines_matched{$line} = 1; } } } print foreach @all_found; print "\nNow the uniques:\n"; print foreach keys %lines_matched; __DATA__ Joe is lazy Robin Wood Mary Poppins Francis Bacon Ruppert Joe married Mary

outputs

Joe is lazy Joe married Mary Mary Poppins Joe married Mary Francis Bacon Now the uniques: Francis Bacon Joe married Mary Joe is lazy Mary Poppins

update. added \b after reading kyle's comment.


Comment on Re: Nested foreach problem
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://705275]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2014-10-24 09:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (131 votes), past polls