Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

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


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?

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2015-11-28 11:38 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (741 votes), past polls