读取文本文件并使用perl将每一行存储在变量中

时间:2017-11-02 06:36:47

标签: perl

我有一个包含一些数据的文本文件(sample.txt)。我想读取文本文件并将每一行存储在数组或变量中。

sample.txt的

ab1234
str:abcd
pq4567

如何使用perl脚本将这些行中的每一行存储在数组或变量中。

3 个答案:

答案 0 :(得分:2)

很容易。我们打开文件,在chomped \n(换行符)之后将文件中的每一行推到一个数组中并测试它,我们打印数组。 此处$_是从文件中读取的每一行,其中@lines将每个$_存储在一个数组中。

use strict;
use warnings

my $file = "sample.txt";
open(my $fh, "<", "sample.txt") or die "Unable to open < sample.txt: $!";
my @lines;
while (<$fh>) {
chomp $_;
push (@lines, $_);
}
close $fh or die "Unable to open $file: $!";
print @lines;

更简单的方法是将内容存储到数组中。

use strict;
use warnings

my $file = "sample.txt";
open(my $fh, "<", "sample.txt") or die "Unable to open < sample.txt: $!";
my @lines = <$fh>;
chomp(@lines);
print @lines;

答案 1 :(得分:0)

# open the file
open my $fh, '<', 'sample.txt'
  or die "Could not open sample.txt: $!";

# Read the file into an array
my @lines = <$fh>;

# Optionally, remove newlines from all lines in the array
chomp(@lines);

答案 2 :(得分:0)

如果您能够使用CPAN模块,那么Tie::File可以为您提供帮助。 使用此模块,您可以修改,添加或删除文件中的内容。

下面是

脚本。

#!/usr/bin/perl

use strict;
use warnings;
use Tie::File;

my @contents=();

tie @contents, 'Tie::File','sample.txt' or die "Not able to Tie sample.txt\n";

my $count=1;
foreach (@contents)
{
    print "line $count:$_\n";
    $count++;
}

untie @contents;

输出:

line 1: ab1234
line 2: str:abcd
line 3: pq4567
相关问题