How do you read file content into an array in Perl?
In Perl, you can use the open function to open a file and the <> operator to read the file content line by line into an array. Here is an example code:
my $file = "example.txt";
open(my $fh, "<", $file) or die "Cannot open file: $!";
my @lines = <$fh>;
close($fh);
foreach my $line (@lines) {
chomp($line); # 去除每行末尾的换行符
print "$line\n";
}
In the example above, we first use the open function to open a file named example.txt, then use the <> operator to read the file contents line by line into the @lines array. Finally, we use a foreach loop to iterate through the array and print each line.
It is important to remember to call the close function to close the file handle after using the file.