免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3467 | 回复: 7
打印 上一主题 下一主题

求教 如何从文件中每次读取固定数目的行 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-07-16 17:42 |只看该作者 |倒序浏览
20可用积分
比如一个文本文件,我想做个循环,每次读入10行进行操作,请问有什么简单些的方法实现没有?

多谢了先

最佳答案

查看完整内容

package MyFileIO;use base 'IO::File';sub get_n_lines { my $self = shift; my $lines = shift || 1; #default for 1 line. if (wantarray) { my @t; for (1 .. $lines) { push @t, $self->getline; } return @t; } my $t; for (1 .. $lines) { $t .= $self->getline; } return $t;}1;------#! /usr/bin/env perluse strict;use warnings;use MyFileIO;my $file = MyFileIO->new('test.pl') or die;my $test = $file->ge ...

论坛徽章:
0
2 [报告]
发表于 2008-07-16 17:42 |只看该作者
package MyFileIO;

use base 'IO::File';

sub get_n_lines {
        my $self = shift;
        my $lines = shift || 1;  #default for 1 line.

        if (wantarray) {
                my @t;
                for (1 .. $lines) {
                        push @t, $self->getline;
                }

                return @t;
        }

        my $t;
        for (1 .. $lines) {
                $t .= $self->getline;
        }

        return $t;
}

1;


------

#! /usr/bin/env perl

use strict;
use warnings;

use MyFileIO;

my $file = MyFileIO->new('test.pl') or die;

my $test = $file->get_n_lines(10);

print $file->get_n_lines(10);

print $test;
___________________

给你写一个吧,现在挣个工分可真不容易啊

论坛徽章:
0
3 [报告]
发表于 2008-07-16 19:57 |只看该作者
sub read_n_lines {
        # read_n_times...
}



[ 本帖最后由 cobrawgl 于 2008-7-16 20:24 编辑 ]

论坛徽章:
0
4 [报告]
发表于 2008-07-16 23:02 |只看该作者
if (wantarray) {
这个,学到了。

论坛徽章:
0
5 [报告]
发表于 2008-07-17 11:20 |只看该作者

回复 #3 cobrawgl 的帖子

你都有那么多分了。俺还得多逛水

论坛徽章:
0
6 [报告]
发表于 2008-07-17 17:26 |只看该作者

回复 #3 cobrawgl 的帖子

学会了.

论坛徽章:
0
7 [报告]
发表于 2008-07-23 16:29 |只看该作者
昨天学了一招
可以试试这段代码:

$lineNum = 1;
while ( $lineNum <= 1000 ) {
        &readTenLines($lineNum);
        print "------------------------------------------------------\n";
        $lineNum += 10;
}
       
sub readTenLines() {
        open FILE, "< file.txt";
        my ($begin) = @_;
        my $end = $begin + 10;
        while (<FILE>) {
                print if ( $. >= $begin && $. <= $end );
        }
        close FILE;
}

论坛徽章:
0
8 [报告]
发表于 2008-07-28 09:52 |只看该作者

多谢各位

在此谢过~
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP