0

我有一个数组,其中元素看起来像这样(包括空格)

@array = (
"    795     0|  1",
"      5   135| 17",
"     12   161| 17",
"    244    22| 17",
"     11    25| 17",
"    249   389| 17",
"  22383   443| 17"
);

我需要取出一个元素

"    795     0|  1"

并将其拆分为 3 个数字,去掉空格和“|” 在每一行。

@new_array =("795","0","1");

我遇到的问题是数字的空格和大小各不相同。

4

4 回答 4

4

我会使用只匹配数字的正则表达式:

#!/usr/bin/perl

use strict ;
use warnings ;
use Data::Dumper ;

my @array = (
"    795     0|  1",
"      5   135| 17",
"     12   161| 17",
"    244    22| 17",
"     11    25| 17",
"    249   389| 17",
"  22383   443| 17"
);

foreach my $item ( @array ) {
  my @tmp = $item =~ m/(\d+)/g ;
  printf "'%s' => %s\n" , $item , Dumper( \@tmp ) ;
}

如果字符串开头没有空格,这也将起作用。

于 2012-04-11T21:02:58.013 回答
3

单程:

my ($empty, @array)  = split(/\|?\s+/, "    795     0|  1");
于 2012-04-11T20:52:23.400 回答
1

也许像这样更容易和可读的东西可以帮助:

#!/usr/bin/perl

use strict;
use warnings;

my @array = (
"    795     0|  1",
"      5   135| 17",
"     12   161| 17",
"    244    22| 17",
"     11    25| 17",
"    249   389| 17",
"  22383   443| 17"
);

my $eggs;

for my $spam (@array) {
    chomp $spam;
    $spam =~ s/^\s*//;
    push @$eggs,  [ split ( /\|?\s+/, $spam ) ];
}

for my $egg (@$eggs) {
    print join (", ", @$egg);
    print "\n";
}

结果是:

795, 0, 1
5, 135, 17
12, 161, 17
244, 22, 17
11, 25, 17
249, 389, 17
22383, 443, 17
于 2012-04-12T14:01:18.357 回答
0

If you're spacing is truly uniform, you could use Perl's unpack to get at the data. See http://perldoc.perl.org/perlpacktut.html#Packing-Text

于 2012-04-12T03:43:17.270 回答