Reputation: 83
I am trying to pass all the data from a file into a Perl array and then I am trying to use a foreach loop to process every string in the array. The problem is that the foreach instead of printing each individual line is printing the entire array.I am using the following script.
while (<FILE>) {
$_ =~ s/(\)|\()//g;
push @array, $_;
}
foreach $n(@array) {
print "$n\n";
}
Say for example the data in the array is @array=qw(He goes to the school everyday)
the array is getting printed properly but the foreach loop instead of printing every element on different line is printing the entire array.
Upvotes: 2
Views: 257
Reputation: 1377
Since the entire file is just one line.You can split the string on basis of whitespace and print every element of array in new line
use strict;
use warnings;
open(FILE,'YOURFILE' ) || die ("could not open");
my $line= <FILE>;
my @array = split ' ',$line;
foreach my $n(@array)
{
print "$n\n";
}
close(FILE);
Input File
In recent years many risk factors for the development of breast cancer that .....
Output
In
recent
years
many
risk
factors
for
the
development
of
breast
cancer
that
.....
Upvotes: 0
Reputation: 67910
After reading your comments, I am guessing that your problem is that your source file does not contain any newlines: I.e. the entire file is just one line. Some text editors just wrap the text without actually adding any line break characters.
There is no "solution" to that problem; You have to add line breaks where you want them. You could write a script to do it, but I doubt it would make much sense. It all depends on what you want to do with this text.
Here's my code suggestions for your snippet.
chomp(@array = <FILE>);
s/[()]//g for @array;
print "$_\n" for @array;
or
@array = <FILE>;
s/[()]//g for @array;
print @array;
Note that if you have a file from another filesystem, you may get \r
characters left over at the end of your strings after chomp
, causing the output to look corrupted, overwriting itself.
Additional notes:
(\)|\()
is better written as a character class: [()]
.@array = <FILE>
will read the entire file into the array. No need
to loop.print
can be assigned a list of items
(e.g. an array) as arguments. And you can have a postfix loop to
print sequentially.$_
,
which is a handy way to do substitutions on the array.Upvotes: 0