Perl读取文本格式化后写入文本


demo:

#!/usr/bin/perl -w
#Perl pragma to restrict unsafe constructs
use strict;
use utf8;

#main function
sub main {
    #get params
    # @_  
    # Within a subroutine the array @_ contains the parameters passed to that subroutine. 
    # Inside a subroutine, @_ is the default array for the array operators push, pop, shift, and unshift.
	# set source file location
    my $s_file = "example_file.txt";
	# set destinate file location
    my $d_file = "file_1.txt";
	# notice and exit if $s_file or $d_file is null
    die "must have source file and destination file!\n" unless $s_file && $d_file;

    #open file for read, FO file handler
    if ( open(FO, $s_file) ) {
        if ( open(FOO,">$d_file") ) {
            #do while loop 
            while(<FO>) {
                # $_ general variables 
                my $line = $_;
                # remove head and tail blank
                $line =~ s{^\s|\s$}{}g;
                # use , split line
                # split /PATTERN/,EXPR. use what split depend on your file delimiter
                my @items = split/,/, $line;
                # write some item to new file
                print FOO  $items[1] . "|" . $items[0] . "  ";
            }
            # close file handler
            close(FOO);
        } else {
			# open file fail
            print "open destination file $d_file error\n";
        }
		# close file handler
        close(FO);
    } else {
		# open file fail
        print "open source file $s_file error\n";
    }
}

# pass params to main function,
# @ARGV
# The array @ARGV contains the command-line arguments intended for the script.

main(@ARGV);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值