2

我有一个包含元素的数组

@array=("link_dm &&& drv_ena&&&1",
        "txp_n_los|rx_n_lost",
        "eof &&& 2 &&& length =!!!drv!!!0");

我想获取第一个“&&&”之前的所有字符,如果元素没有“&&&”,那么我需要提取整个元素。

这是我要提取的:

likn_dm
txp_n_los|rx_n_lost
eof

我用了

    foreach my $row (@array){
      if($row =~ /^(.*)\&{3}/){
        push @firstelements,$1;
      }
    }

但我越来越

link_dm &&& drv_ena
txp_n_los|rx_n_lost
eof &&& 2

有人可以建议我如何实现这一目标吗?

4

4 回答 4

3

也许只是splitting 会有所帮助:

use strict;
use warnings;

my @array = (
    "link_dm &&& drv_ena&&&1",
    "txp_n_los|rx_n_lost",
    "eof &&& 2 &&& length =!!!drv!!!0"
);


foreach my $row (@array){
    my ($chars) = split /\&{3}/, $row, 2;
    print $chars, "\n"
}

输出:

link_dm 
txp_n_los|rx_n_lost
eof 
于 2013-07-18T03:51:06.813 回答
0

如果您使用正则表达式,请使用最小跨越模式:.*?. 请参阅perldoc perlre http://perldoc.perl.org/perlre.html

#!/usr/bin/env perl

use strict;
use warnings;

# --------------------------------------

use charnames qw( :full :short   );
use English   qw( -no_match_vars );  # Avoids regex performance penalty

use Data::Dumper;

# Make Data::Dumper pretty
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent   = 1;

# Set maximum depth for Data::Dumper, zero means unlimited
local $Data::Dumper::Maxdepth = 0;

# conditional compile DEBUGging statements
# See http://lookatperl.blogspot.ca/2013/07/a-look-at-conditional-compiling-of.html
use constant DEBUG => $ENV{DEBUG};

# --------------------------------------

my @array = (
    "link_dm &&& drv_ena&&&1",
    "txp_n_los|rx_n_lost",
    "eof &&& 2 &&& length =!!!drv!!!0",
);

my @first_elements = ();
for my $line ( @array ){

  # check for '&&&'
  if( my ( $first_element ) = $line =~ m{ \A (.*?) \s* \&{3} }msx ){
    push @first_elements, $first_element;
  }else{
    push @first_elements, $line;
  }
}
print Dumper \@first_elements;
于 2013-07-18T12:55:00.247 回答
0
for (@array) {
    print "$1\n" if /([^ ]*)(?: *[&]{3}.*)?$/;
}
于 2013-07-18T04:19:15.927 回答
0

你可以写:

@firstelements = map { m/^(.*?) *&&&/ ? $1 : $_ } @array;

或者,如果您喜欢foreach一遍mapif一遍?:

foreach my $row (@array){
  if($row =~ /^(.*)\&{3}/) {
    push @firstelements, $1;
  } else {
    push @firstelements, $row;
  }
}
于 2013-07-18T01:56:39.647 回答