Assuming the specification is, “print the key phrase together with the following text up to 250 characters,” the regex would be better as /(web site.{0,250})/, which also matches when the key phrase is followed by fewer than 250 characters of text before the end of the file. As this match is greedy, it will match the largest number of characters up to 250.
Athanasius <°(((>< contra mundum
| [reply] |
This is what I have so far...
open (OUTPUT, ">Results.txt") || die ("Could not open file results.txt; $OS_ERROR");
open( INFILE, "Textfile.txt" )or die("Can not open input file: $!");
while (<INFILE>) {
if ($ARG =~ /Something/ ) {
print OUTPUT $ARG ;
}
}
close (OUTPUT);
| [reply] |
use strict;
use warnings;
open (my $out, ">", "Results.txt") or die ("Could not open file Result
+s.txt; $!");
open (my $in, "<", "Textfile.txt") or die ("Can not open input file: $
+!");
local $/;
while (<$in>) {
if (/(web site.{250})/i) {
print $out $1;
}
}
Changes that I made include:
- I swapped to lexical file handles and 3 argument open, which are considered better practice for a number of reasons. See perlopentut. In particular, this gives strict more power to help and removes the need for explicit close.
- I corrected inconsistency between your file name and error message; file names are generally case sensitive.
- I swapped to slurp mode using $/. Given the large number of characters you are interested in, it is unlikely they will all fall on the same line.
- Your while(<>) loop read data into $_ not $ARG, so I corrected that.
- I swapped your regular expression to the regular expression I posted above, with the addition of the s modifier. This makes it so . also matches new lines, and is essential when working in slurp mode.
You may consider going to http://learn.perl.org to gather some learning resources before trying to run too far.
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
| [reply] [d/l] [select] |
open (OUTPUT, ">Results.txt")
open( INFILE, "Textfile.TXT" )
while (<INFILE>) {
if ($ARG =~ /(Something.{0,250})/ ) {
print OUTPUT $ARG ;
}
}
close (OUTPUT);
The "regexp" suggested is not working.
Thoughts? | [reply] [d/l] |