【问题标题】:Print the next line after the pattern match using perl使用 perl 在模式匹配后打印下一行
【发布时间】:2020-06-02 07:52:09
【问题描述】:

之前有一个类似的问题,但我的问题有点不同。所以我修改了一下并在这里发布寻求帮助。

 Car Type, Price,  Colour,

 N17,       200$    white    
 A57,       250$    Red     
 L45,       350$    Black  

以下是我目前拥有的代码。

my @cartype;
while (@cartype = <FH1> ) {

    my $i = 0;

    foreach my $a (@cartype) {
        if ($a =~ m/(Car)/ )  {
            my $b = $cartype[$i+1];
            push (@cartype, $b);
            print $b;
        }

        $i++;
    }
}

close;

当前输出:

 N17,       200$    white    
 A57,       250$    Red     
 L45,       350$    Black

我想在模式匹配后打印下一行,但它正在打印整个下一行,而不是我只需要那个特定的列,比如如果我正在搜索一个名为“汽车”的模式,只有汽车类型应该显示而不是整个下一行。

预期输出:

    Car Type              
       N17             
       A57                 
       L45              
       ..               
       .                

【问题讨论】:

  • 听起来您要求输出整列(包括所有行),而不是仅在匹配之后的行中的值,对吗?
  • 是的,整列都必须是输出。
  • 乍一看,这看起来很像一个 CSV 文件,所以我打算建议使用 Text::CSV_XS。但是在提供的输入中,除了标题行之外,第二个和第三个字段之间没有逗号分隔符。这是正确的,还是应该在 $ 符号后加逗号? Text::CSV_XS 可能仍然有用,但您必须手动拆分第二个和第三个字段。
  • 抱歉这里的错字,$符号后面会有一个逗号。

标签: arrays regex perl


【解决方案1】:

为什么不以追随的精神尝试一些事情呢?

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my $debug = 0;      # debug flag

my $look_for = shift || usage();

my %cars;

my @header = map{ s/(^ +| +$)//; $_ } (split ',', <DATA> );

chomp @header;      # clean up header fields

say Dumper(\@header) if $debug;

while(<DATA>) {
    next if /^ *$/;                             # skip empty lines
    chomp;                                      # snip eol
    if( /(\w\d{2}), +(\d{3}\$) +(\w+)/ ) {      # our data
        @{$cars{$1}}{@header} = ($1,$2,$3);     # fill %cars with data
    }
}

say Dumper(\%cars) if $debug;

$look_for = 'Car Type' if $look_for eq 'Car';
$look_for = 'Car Type' if $look_for eq 'Type';

say "\nLooking for: $look_for\n";

while( my($k,$v) = each %cars ) {
    say "  " . $v->{$look_for};                 # print field of interest
}

sub usage {
    say 
"
    USAGE: $0 [Car|Type|Colour|Price]
";
    exit 0;
}

__DATA__
Car Type, Price,  Colour

N17,       200$    white
A57,       250$    Red
L45,       350$    Black

【讨论】:

  • 我无法使用 Data::Dumper 功能。我也无法安装。
  • Data::Dumper 是一个核心模块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
相关资源
最近更新 更多