您的位置:首页 > 运维架构

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

2013-12-13 13:43 141 查看
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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息