简体   繁体   中英

Include file data in Perl array

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.

After reading your comments, I am guessing that your problem is that your source file does not contain any newlines: Ie 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.
  • As shown in my examples, print can be assigned a list of items (eg an array) as arguments. And you can have a postfix loop to print sequentially.
  • With a (postfix) loop, all the loop elements are aliased to $_ , which is a handy way to do substitutions on the array.

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
.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM