for (@array) {
do {something($_)}
if -1 != index( $_, 'bar');
}
For more complicated matching, you probably want a regex match,
# . . .
if m/foo|bar|baz/;
| [reply] [Watch: Dir/Any] [d/l] [select] |
I suggest using grep to search strings in array, or to find number of elements matching a criteria. The points are demonstrated in the code below:
use strict;
use warnings;
use Data::Dumper;
my @GrepList = ("yesterday", "today", "tomorrow") ;
# look for all elements with "to" in the string
my @ElementList = grep(/to/i, @GrepList) ;
print Dumper(@ElementList);
## In list context, returns the count of number of elements
## that meet the search criteria
my $ElementsFound = grep(/to/i, @GrepList) ;
print $ElementsFound;
Hope this helps
May the force be with you | [reply] [Watch: Dir/Any] [d/l] |
$foo is not an array, it is a scalar. You could use index to find 'bar' in $foo, but that doesn't sound like what you want. Perhaps you should post the rest of you code and some sample data so we can see what you are trying to do.
Perl is Huffman encoded by design.
| [reply] [Watch: Dir/Any] |
I know $foo isnt an array, I was just using that as an example.
a better example might be:
for ($num=0; $num<=100; num++){
if (@text[$num] contains 'string'){
$cnt++;
}
}
print "string was found on $cnt lines"
| [reply] [Watch: Dir/Any] [d/l] |
I would probably re-write it a bit
untested
use strict;
use warnings;
open (IN, 'myfile.txt') or die $!;
my @lines = <IN>;
my $cnt = 0;
for my $line (@lines) {
if ($line =~ /somekeyword/) {
$cnt++;
}
}
print ("somekeyword was found in $cnt lines\n");
You could shorten this code a LOT but wanted to make it a little more explicit.
NOTE: You don't have to necessarily put the whole file in an array. You can use while(<IN> and check that way too. | [reply] [Watch: Dir/Any] [d/l] [select] |
| [reply] [Watch: Dir/Any] |
Perl provides a rich language for searching for patterns within strings via its Regular Expression engine.
perldoc perlre
This will give you way more info than you can absorb quickly. Now, based on your original post, you want to iterate over an array and check each element for a pattern (in this case, a string) and do something each time you find a match.
for my $line (@input) {
if ($line =~ /$pattern/) {
# Do something
print "$line contains $pattern\n";
}
}
If you just want to get a count of lines that contain $pattern, Perl has a grep function (see perldoc -f grep for more on grep). It returns a list of matches based on some test. When evaluated in scalar context, the length of that list, or the number of matches, is returned.
my $match_cnt = grep { $_ =~ /$pattern/ } @input;
With Perl, there is always more that one way to do things, but some are obviously better and more appropriate based on your needs.
Ivan Heffner
Sr. Software Engineer, DAS Lead
WhitePages.com, Inc.
| [reply] [Watch: Dir/Any] [d/l] [select] |