in reply to putting text into array word by word

In the "open", I would not use the file mode '+>' if you only intend to read the file.

#!usr/bin/perl -w use strict; open FILE, '<', "input.txt" or die "unable to open input.txt"; # the $! variable adds the O/S specific info, but it is not # not always that useful. my @all_words; while (<FILE>) { my @these_words = split(' ', $_); foreach my $this_word (@these_words) { push @all_words, $this_word; } }
#to count the words: use Data::Dumper; my %words; while (<FILE>) { my @these_words = split(' ', $_); foreach my $this_word (@these_words) { $words{$this_word}++; } } print Dumper \%words;

Replies are listed 'Best First'.
Re^2: putting text into array word by word
by Anonymous Monk on Jan 09, 2012 at 18:31 UTC

    No foreach loop required. You can push several values at once: push @all_words, @these_words;

Re^2: putting text into array word by word
by jms53 (Monk) on Jan 09, 2012 at 18:50 UTC
    I have added  print "$this_word";

    and

     print $this_word;

    in the foreach loop, yet nothing is printed

      Your file "open mode" is wrong, use '<' for read-only.
      #!/usr/bin/perl -w use strict; my @words; open FILE, "<", "input.txt" or die "unable to open input.txt $!"; print "file loaded \n"; while (<FILE>) { @words = split(' ', $_); push @all_words, @words; } foreach $word (@words) { print "$word\n"; } __END__ # if you want to count the words # then that is different - use a hash # table of "word => count" #the default split (/\s+/,$_) #differs only between this special case split(' ',$_) #in how it handles a "null" field at the beginning of the line my %words; while (<FILE>) { my @words = split; foreach my $word (@words) { $words{$word}++; } } === or === my %words; while (<FILE>) { foreach my $word (split) { $words{$word}++; } } ==== or === my %words; while (<FILE>) { $words{$_}++ foreach (split); }