Text Processing using regular expression
Specification
given a file like this,there are three field divided by | : |
abc-efg012.123. |one|two
second-of WGF|two|three
second-of||three
forth-of|one|
write a perl script,
- for the first field, extract from the beginning untill a . or space.
- exchange the place of the second the third part
Solution 1
use v5.14;
my @input;
while(<DATA>) {
chomp;
my @fields = split /\|/;
$fields[0] =~ /([^\.\s]+)/;
$fields[0] = $1;
push @input, \@fields
}
say "$_->[0]|$_->[2]|$_->[1]" for (reverse @input);
__DATA__
abc-efg012.123. |one|two
second-of WGF|two|three
second-of||three
forth-of|one|
Solution 2
use regular expression
my @input;
while(<DATA>) {
s/([^\.\s]+).*?(?=\|)/$1/;
s/\|(.*)\|(.*)\Z/\|$2\|$1/;
push @input, $_;
}
print for (reverse @input);
__DATA__
abc-efg012.123. |one|two
second-of WGF|two|three
second-of||three
forth-of|one|