How to split a text file line by line in Perl
A commonly asked question is "how to split a text file line by line".
Read line by line
Normally you would read the file line by line, so the code is:
open my $in, "<:encoding(utf8)", $file or die "$file: $!"; while (my $line = <$in>) { chomp $line; # ... } close $in;
Read all the lines at once
Alternatively you might want to read the whole file into memory at once and hold it in an array where each line is a separate element:
open my $in, "<:encoding(utf8)", $file or die "$file: $!"; my @lines = <$in>; close $in; chomp @lines; for my $line (@lines) { # ... }
The latter has the disadvantage that it can only handle files that will fit into the memory of the computer, but sometime it is mor convenient to have all the file in memory at once.
split
Finally, if you really want to use the split function, you could read the whole file into memory using slurp and then split it along the newlines, though I don't know when would this have any advantage over the other methods.
my @lines = read_lines('some_file.txt'); sub read_lines { my ($file) = @_; open my $in, "<:encoding(utf8)", $file or die "$file: $!"; local $/ = undef; my $content = <$in>; close $in; return split /\n/, $content; }
Published on 2015-10-21