I have a string of text that should have 1 or more sub string inside brackets whats the best way to extract each wanted sub string, I then need to do stuff with each of these
The code bellow only grabs the first "Wanted"
print "Hello World!\n";my $text = "Lorem ipsum dolor sit amet,(Wanted 1) consectetur adipiscing elit. (Wanted 2) (Wanted 3) Nunc bibendum ante diam, a imperdiet purus (Wanted 4) faucibus a. Pellentesque ultricies nibh.";my @WantedText;if($text =~ m/\((.*?)\)/ ) { push @WantedText, $1; } foreach my $want (@WantedText){ print $want . "\n"; }
Dave's looks more complete to me, Trev. He's included the shebang line (#!...), some "use" lines, putting the data into a variable. And he provided it before Norie did.
The section that Norie provided looks more verbose, but what's more complete about it? What did Dave fail to include which Morie included? What does Dave's code do which Norie's doesn't?
Norie's doesn't do anything by itself. Dave's does - it's a complete script. I'm not saying Norie's is wrong, but I can't see how it's more complete.
Are you aware that you can give credit to more than one answer, Trev?
Here's an even less "complete" version for you, based on Dave's /g trick:
my $text = "Lorem ipsum dolor sit amet,(Wanted 1) consectetur adipiscing elit. (Wanted 2) (Wanted 3) Nunc bibendum ante diam, a imperdiet purus (Wanted 4) faucibus a. Pellentesque ultricies nibh.";print join("\n", $text =~ /\((.*?)\)/g) . "\n";
The above doesn't store an array of the results, but I'm not sure you need that or whether just printing results will do.
The output is:
Wanted 1
Wanted 2
Wanted 3
Wanted 4
Open in new window