gpt4 book ai didi

perl - 如何删除具有特定字符的整个数组

转载 作者:行者123 更新时间:2023-12-02 04:24:43 25 4
gpt4 key购买 nike

我有一个从 .xls 文件中提取的 perl 代码。我的 .xls 文件如下所示

NUMBER    NAME    ALPHABET
one Jane a
two Adam b
three Josh c
;four
five Agnes e
six Mary f
;seven
eight Lara h

我想提取信息,只提取第 1 列和第 2 列。我的 perl 代码如下。

     #!/usr/bin/perl

use warnings;
use strict;
use Spreadsheet::ParseExcel;

main ();

sub main {

my $filename = 'Book1.xls';
my $parser = Spreadsheet::ParseExcel->new();
my $workbook = $parser->parse( $filename );

if ( !defined $workbook ) {
die "-E-: cannot parse <$filename>.\n ", $parser->error(), ".\n";
}

my $worksheet = $workbook -> Worksheet ( 'a' ) || die "-E-: cannot parse family pin list.\n";
my ( $row_min, $row_max ) = $worksheet-> row_range();

open ( my $file,"> output.txt");

for my $row ( 1 .. $row_max ) {

my @data;

for my $col ( 0 ) {
my $number = $worksheet-> get_cell( $row, $col );
if ( $number ) {
push @data, $number-> value();
}
else {
push @data, '';
}
}

for my $col ( 2 ) {
my $alphabet = $worksheet->get_cell( $row, $col );
if ( $alphabet ) {
push @data, $alphabet->value();
print $file "@data\n";
}
else {
push @data, '';
}
}

}

close $file;

print "done\n";
}

结果是

    one a
two b
three c
;four
five e
six f
;seven
eight h

我想删除以字符串“;”开头的整个数组。我像下面这样扩展我的代码

        open ( my $file,"> output.txt");

for my $row ( 1 .. $row_max ) {

my @data;

for my $col ( 0 ) {
my $number = $worksheet-> get_cell( $row, $col );
if ( $number ) {
push @data, $number-> value();
}
else {
push @data, '';
}
}

for my $col ( 11 ) {
my $alphabet = $worksheet->get_cell( $row, $col );
if ( $alphabet ) {
push @data, $alphabet->value();
}
else {
push @data, '';
}
}


my @new_data = grep(!/;/, @data);
my @latest_data = grep ( $_ ne '', @new_data);
print $file "@latest_data\n";


}

close $file;

print "done\n";
}

输出结果如下。

     one a
two b
three c

five e
six f

eight h

我不想成为一片空白。我想如何消除产生如下结果的空白区域?

     one a
two b
three c
five e
six f
eight h

我也试过这样做,但结果是一样的。

     for my $index (reverse 0..$#data) {
if ( $data[$index] =~ /^;/ ) {
splice(@data, $index, 1);
}
}
print $file "@data\n";

最佳答案

希望您正在寻找next

use warnings;
use strict;

@data=("one a", "two b","three c", ";four d","five e","six e","seven g","eight h")
for(@data){
next if (/^;/);
print $_,"\n";
}

关于perl - 如何删除具有特定字符的整个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55821583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com