perl - a simple task exerice, split and loop

it is a very simple task to exercise your understanding of the perl language. 

 

the issue is like this : 

 

 

 

$ cat test.txt

a,1,x,A,B,C

b,2,y,D

c,3,z,E,F

 
 
and you want to display the final result as follow.
 
a,1,x,A
a,1,x,B
a,1,x,C
b,2,y,D
c,3,z,E
c,3,z,F
 
Below shows some techinques.
 
perl -F, -lane '$k=3;for $f (@F[$k..$#F]) { print join(",", @F[0..$k-1]), ",$f" }' test.txt
 
and you can also write the following script files.
 
#! /bin/perl


# you may also run the following command on the command line,
#  perl -F, -lane '$k=3;for $f (@F[$k..$#F]) { print join(",", @F[0..$k-1]), ",$f" }' test.txt

while (<STDIN>) {
    while ($_ =~ /^([a-z0-9,]+)?([A-Z0-9,]+)/g) {
        map {print "$1$_\n" } split (/,/, $2) ;
    }

}
 
 
or 
 
#! /bin/perl



# you may also run the following command on the command line,
#  perl -F, -lane '$k=3;for $f (@F[$k..$#F]) { print join(",", @F[0..$k-1]), ",$f" }' test.txt

$k = 3;
while (<>) {

    @F = split(",", $_);
    for $f (@F[$k..$#F]) {
        print join(",", @F[0 .. $k - 1]), ",$f\n";
    }
}
 
 
Or you can do this following line as well.
 
$ perl -F, -lane '($a,$b,$c,@o) = @F; print "$a,$b,$c,$_" for (@o); ' 
 
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值