in reply to Modifying text file

I am smelling an XY Problem. So here is some code that takes $text and creates an array @words containing all the words in $text. In addition, it adds a comma to each word, but my guess is, that you are not really interested in that...

use strict; use warnings; my $text = <<EOTEXT; This is a word. Here is another sentence. EOTEXT my @words = $text =~ /\b(\w+)\b/g; print "@words\n"; $_.="," for @words; print "@words\n";

Thanks to toolic for the sample text.

Replies are listed 'Best First'.
Re^2: Modifying text file
by torres09 (Acolyte) on Jun 06, 2013 at 03:34 UTC
    Sir

    I actually want it , i.e. I want that each word in the text file should be in an array , with a comma in between .Even the spaces

      Apologies if you perceived my answer as being patronizing.

      If you want to split your text into words AND keep the spaces, split might be an alternative. Using a capture group in the regex in split, the delimiters are not discarded. So splitting on words will give you the words and the characters inbetween:

      use strict; use warnings; use Data::Dumper; my $text = <<EOTEXT; This is a word. Here is another sentence. EOTEXT my @words = split /\b(\w+)\b/, $text; print Dumper \@words;

      results in

      $VAR1 = [ '', 'This', ' ', 'is', ' ', 'a', ' ', 'word', '. ', 'Here', ' ', 'is', ' ', 'another', ' ', 'sentence', '. ' ];