in reply to find a string a certain number of times
If you have an array, @file, then you have to loop through it. m// cannot loop through an array in perl5 (maybe perl 6?). However, if you put the entire file into a scalar, now we can get somewhere:
That said, grep would use up less space, which may be important for large files. The reason is because you're duplicating the file in both an array and a scalar. The obvious way to overcome that is to put it in the scalar to begin with - which means you don't have an array later if you want to look up lines in an array.my $file = join '', @file; # put it all in a single scalar if ($file =~ m/(?:what you want to find.*){6}/) { print "'what you want to find' was in the file at least 6 times.\n"; }
Of course, for really large files, you'll want to iterate through the file one line at a time to keep from loading 100MB of text into memory at once:
And, of course, this means you don't have the file in memory at all when you're done, which may not be what you want either.my $count; while (<$fh>) { $count++ while /what you want to look for/g; if ($count >= 6) { last; } } $fh->close(); if ($count >= 6) { print "found 'what you want to look for' at least 6 times in the fil +e.\n"; }
|
|---|