Gavin has asked for the wisdom of the Perl Monks concerning the following question:

Hi Brethren,
I would like to split a text file into an array but retain the full stops for future use as below.
Thank you in anticipation
my($line, @line); while(<IN>) { $line=$_; chomp($line); @line = split(/\./,$line); foreach(@line){ print OUT "$_\n"; } }

Replies are listed 'Best First'.
Re: Perl split
by Tanktalus (Canon) on Mar 12, 2006 at 15:21 UTC

    McDarren's response will get you the full stops in a separate entry in the array. The other alternative is using zero-width assertions. In this case, I suspect you want the full stop associated with the sentence before, so I would use a look-behind assertion since you want to split in between the full stop and the next character.

    @line = split (/(?<=\.)/, $line);

      Thanks all
      Tanktalus got it right,
      I did want to keep the formatting.
Re: Perl split
by McDarren (Abbot) on Mar 12, 2006 at 14:37 UTC
    "..but retain the full stops for future use.."

    Just use capturing parentheses with your split. eg:

    @line = split(/(\.)/,$line);
    Update: I guess I should have explained a little. From perldoc -f split:
    If the PATTERN contains parentheses, additional list elements are crea +ted from each matching substring in the delimiter.

    The best way to understand this is by example:

    while(<DATA>) { $line=$_; chomp($line); @line = split(/(\.)/,$line); } print Dumper(@line); __DATA__ The quick. Brown fox. Jumps over the. Lazy dog.
    Which gives:
    @line = ( 'The quick', '.', ' Brown fox', '.', ' Jumps over the', '.', ' Lazy dog', '.' );

    Cheers,
    Darren :)

Re: Perl split
by thor (Priest) on Mar 12, 2006 at 14:34 UTC
    What does the code you provided not do that you want it to do? Providing sample input and desired output would be helpful in answering your question...

    thor

    The only easy day was yesterday