Perl学习笔记二: 尝试优化文件读取

这篇博客记录了作者在尝试优化Perl程序文件读取速度的过程中,将逐行读取改为一次性读取整文件到数组的过程。尽管预计这会提高效率,但实测结果显示程序运行反而变慢,耗时0.608秒。作者对此现象的原因展开后续研究。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上次笔记中的Perl程序在读取文件时是一行一行读入的,作者猜想应该比较慢。今天作者试图提高文件读取的速度。

 

因为Perl允许将文件内容全部读入到一个数组变量中,所以作者将上次的程序修改如下:

 

#!/usr/bin/perl -w

# Usage: fjoin.pl <dir>
# This program print all .cpp/.h files in <dir> to stdout

use 5.010;
use strict;
use warnings;

# Sub: print a file to stdout
# Arguments:
#     $_[0]  The file name
sub printFile
{
    my $success = open FHANDLE, "<", $_[0];
    my @lines;

    if(! $success)
    {
        return;
    }

    @lines = <FHANDLE>;
    close FHANDLE;

    foreach (@lines)
    {
        print $_;
    }
    #if(@lines)
    #{
        # If the last line doesn't end with a LF, append one.
        #if(!($lines[@lines - 1] =~ //n$/))
        #{
            #print "/n";
        #}
    #}
}

# The main program
my $dir = $ARGV[0];
my @allFiles;
my $file;

if(!defined($dir))
{
    die "Directory not defined";
}

# Iterate all files in the dir
@allFiles = <$dir/*>;

if(! @allFiles)
{
    die "Can not open the directory $dir";
}

foreach $file (@allFiles)
{
    if($file =~ //.cpp$/)
    {
        &printFile($file);
    }
    elsif($file =~ //.h$/)
    {
        &printFile($file);
    }
}

 

但是运行结果却反而比上次的更慢,耗时0.608秒。

 

具体原因是什么,有待后续研究。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值