`

perl - a simple task exerice, split and loop

    博客分类:
  • perl
阅读更多

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); ' 
 
 
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics