我正在尝试编写一个脚本,该脚本将获取"|"字符和下一个"|"字符的位置,并将每行这两个位置之间的字符存储到数组中。
文件:
| A| D| MUL|
| D| I| |
| D| V| |
预期输出:添加 DIV MUL
我尝试了下面的代码。 while 循环中可能存在一些问题,并且 $prev_pos 设置为 0。
open ($file, "<$i") or die "couldn't open list";
my $prev_pos=0;
my @store;
my $char ;
while(my $line=<$file>)
{
while ($line =~ /|/g) {
my $pos=$-[0];
my $char = substr($line, $prev_pos+1, $pos-$prev_pos+1);
print "$charn";
if($char =~ /w/)
{
my $prev_char = @store[$pos+1];
@store[$pos+1] = join('',$prev_char,$char);
}
my $prev_pos = $pos;
}
}
}
}
close $file;
请帮忙。
从上一个问题中,您已经知道如何解析各个行:
my @fields = split(/|/, $line, -1);
shift(@fields); # Ignore stuff before first "|"
pop(@fields); # Ignore stuff after last "|"
所以你的问题是关于连接两个数组的元素,逐个索引。
my @merged;
while (<>) {
chomp;
my @fields = split(/|/, $line, -1);
shift(@fields); # Ignore stuff before first "|"
pop(@fields); # Ignore stuff after last "|"
s/^s+|s+z//g for @fields; # Remove leading and trailing spaces.
for my $i (0..$#fields) {
$merged[$i] .= $fields[$i];
}
}
say for @merged;
你把它复杂化了。split
采用正则表达式,并将值抓取到列表中。
然后,您可以使用.
来连接文本来合并后续行:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @merged;
#iterate filehandle line by line - I use the special DATA Filehandle here,
#you should probably use the results of an 'open'.
while ( <DATA> ) {
my $index = 0;
#split the current row on pipe-char "|" and iterate
for my $value ( split /|/ ) {
#use .= to concatenate the value in the @merged array.
$merged[$index++] .= $value;
}
}
#strip whitespace:
s/s+//g for @merged;
#debug, so you can see what's actually being produced.
#note the zero length fields - those are the first and last column.
print Dumper @merged;
#results: (note - probably includes empty values and linefeeds that you
#may need to sanitise).
print "@merged";
__DATA__
| A| D| MUL|
| D| I| |
| D| V| |