【Perl读书笔记】行转换为数组操作split函数

本文是基于《C程序员精通Perl》中3.4节的读书笔记,主要介绍Perl的split函数如何将行数据转换为数组。通过示例展示了如何处理文件`check.file`中的数据,实现了对每行数据进行处理并累加的功能。最终输出显示了逐行处理后的结果以及累计总和。

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

读 《C程序员精通Perl》http://book.douban.com/subject/1232075/   3.4节 笔记




#!/usr/bin/perl

use strict;
use warnings;

my $total = 0;

while (1) {
        my $line = <STDIN>;
        if (not defined($line))
        {   
                print "come to file end\n";
                last;   
        }   

        chomp($line);

        if ($line eq "") #必须放到not defined后边进行判断,因为到了文件尾,
                         #line的值为undef,使用此值的话,会导致出现Use of uninitialized的告警
        {   
                print "come to blank line\n";
                last;   
        }   

        my @check_info = split /\t/, $line;
        $total += $check_info[2];
        printf "%-8s: %-20s %6.2f Total: %5.2f\n", $check_info[0], $check_info[1], $check_info[2], $total; 
}

运行结果:


[root@localhost perl_practice]# cat check.file
01/01/01        a       100
01/01/02        a       100
01/01/03        a       100
01/01/04        a       100
01/01/05        a       100
01/01/06        a       100
[root@localhost perl_practice]# ./check.pl < check.file
01/01/01: a                    100.00 Total: 100.00
01/01/02: a                    100.00 Total: 200.00
01/01/03: a                    100.00 Total: 300.00
01/01/04: a                    100.00 Total: 400.00
01/01/05: a                    100.00 Total: 500.00
01/01/06: a                    100.00 Total: 600.00
come to file end
[root@localhost perl_practice]#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值