简体   繁体   中英

Print the next line after the pattern match using perl

There is a similar question is there before, But mine is little bit different question. so am modifying a bit and posting here for help.

 Car Type, Price,  Colour,

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

Below is the code am having currently.

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;

Current Output:

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

I would like to print next line after the pattern match but it is printing the whole next line, instead of that i just need only that particular column, like if am searching for a pattern called "car" only car types should display instead of whole next line.

Expected Output:

    Car Type              
       N17             
       A57                 
       L45              
       ..               
       .                

Why not to try something in following spirit?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM