将文件行存储到数组中 [英] Storing lines of file into array

查看:72
本文介绍了将文件行存储到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我对Perl还是很陌生,只学习了1周.我正在尝试仅将特定范围的行读取到数组中.如果我在if语句中打印$ _,它将精确列出要存储到数组中的内容.但是将$ _存储到我的数组中,然后在while之外打印@array不会显示任何内容.我不确定该怎么办.我之所以尝试将其存储到数组中的原因也是从列中获取某些信息,因此需要一个数组来这样做.谢谢你的帮助.对你们来说,这可能真的很简单

So I'm pretty new to Perl, only been learning it for 1 week. I'm trying to read only a specific range of lines into an array. If I print $_ inside the if statement, it list exactly what i want stored into my array. But storing $_ into my array and then print @array outside the while shows nothing. I'm not sure what I should do. Reason why I'm trying to store it into an array is too get certain information from the columns, therefore needing an array to do so. Thanks for your help. Its probably really simple for you guys

use strict;
use warnings;

my $filename = 'info.text';
open my $info, $filename or die "Could not open $filename: $!";
my $first_line = 2;
my $last_line = 15;

open(FILE, $filename) or die "Could not read from $filename, program halting.";

my $count = 1;
my @lines;

while(<FILE>){
    if($count > $last_line){
        close FILE;
        exit;
    }
    if($count >= $first_line){
        #print $_;
        push @lines, $_;
    }
    $count++;
}
print @lines;

推荐答案

Perl实际上有一个变量$.,它代表最近使用的File句柄中的当前行:

Perl actually has a variable, $., that represents the current line from the most recently used File handle:

来自perldoc -v $.:

HANDLE-> input_line_number(EXPR)

HANDLE->input_line_number( EXPR )

$ INPUT_LINE_NUMBER

$INPUT_LINE_NUMBER

$ NR

$.

最后访问的文件句柄的当前行号.

Current line number for the last filehandle accessed.

Perl中的每个文件句柄都会计算已读取的行数 从中. (取决于$/的值,Perl的想法是 构成一行可能与您的不匹配.)当从 filehandle(通过readline()或<>),或者在调用tell()或seek()时 在它上面,$.成为该文件句柄的行计数器的别名.

Each filehandle in Perl counts the number of lines that have been read from it. (Depending on the value of $/ , Perl's idea of what constitutes a line may not match yours.) When a line is read from a filehandle (via readline() or <> ), or when tell() or seek() is called on it, $. becomes an alias to the line counter for that filehandle.

您可以使用此变量来大大简化代码:

You can use this variable to drastically simplify your code:

use strict;
use warnings;

my $filename = 'info.text';
open(FILE, $filename) 
   or die "Could not read from $filename, program halting.";

my @lines;
while(<FILE>){
    next unless $. >= 2 && $. <= 15;
    push @lines, $_;
}
close FILE;
print @lines;

您可以将此代码或修改后的版本包装在接受文件句柄,起始行和结束行的子例程中,以使其更加灵活.

You can wrap this code, or a modified version in a subroutine that accepts a filehandle, starting line, and ending line to make it more flexible.

与您的问题无关的另一条注释,建议您

Another note that is unrelated to your problem at hand, it is recommended that you always use three argument open.

这篇关于将文件行存储到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆