使用子例程或函数提取多行记录/数据

时间:2013-04-02 06:04:32

标签: perl

您能告诉我如何使用此代码创建子例程或函数吗? 基本上我想把我的代码变成一个子程序,所以我可以重复使用它而不会让我的脚本太长。

这是我的剧本:

#!/usr/local/bin/perl

use strict;
use warnings;
use Data::Dumper;
use Carp qw(croak);

my @fields;
my ($tmp_var, $rec_type, $country, $header, $Combline, $records, $line);
my $filename = 'data5.txt';

open (my $input_fh, '<', $filename ) or croak "Can't open $filename: $!";
open  my $OUTPUTA, ">", 'drp1.txt' or die $!;
open  my $OUTPUTB, ">", 'drp2.txt' or die $!;
while (<$input_fh>) {
    $line = _trim($_);  
    @fields = split (/\|/, $line);  
    $rec_type = $fields[0];
    $country = $fields[1];
    my $string = substr $fields[1], 0, 1;
    $header = $line if(/^INVHDR/);  

    if ($rec_type eq 'INVDET') {                                     
        if ($string eq 'I')  {           
            $records = $header . $line;                 
            print  $OUTPUTA $records, scalar <$input_fh>;               
        }
        else {           
            $records = $header . $line;
            print  $OUTPUTB $records, scalar <$input_fh>;
        }      
    }     
}   

close $OUTPUTA or die $!;
close $OUTPUTB or die $!;

sub _trim {
    my $word = shift;
    if ( $word ) {      
        $word =~ s/\s*\|/\|/g;      #remove trailing spaces
        $word =~ s/"//g;            #remove double quotes
    }
    return $word;
}

这是我想要放在子例程或函数中的脚本部分:

$line = _trim($_);  
@fields = split (/\|/, $line);  
$rec_type = $fields[0];
$country = $fields[1];
my $string = substr $fields[1], 0, 1;
$header = $line if (/^INVHDR/);

if ($rec_type eq 'INVDET') {                                     
    if ($string eq 'I')  {           
        $records = $header . $line;                 
        print $OUTPUTA $records, scalar <$input_fh>;                
    }
    else {
        $records = $header . $line;
        print $OUTPUTB $records, scalar <$input_fh>;
    }
}     

1 个答案:

答案 0 :(得分:1)

我建议稍微改一点,然后扩展你的_trim函数,把它变成一个解析函数:

use strict;
use warnings;

open( my $input_fh, '<', 'data5.txt' ) or die "Can't open $filename: $!";
open( my $OUTPUTA, '>', 'drp1.txt' ) or die $!;
open( my $OUTPUTB, '>', 'drp2.txt' ) or die $!;

my $header = '';
while (<$input_fh>) {
    if ($_ =~ /^INVHDR/) {
        $header = $_;
    }
    if ($_ =~ /^INVDET/) {
        my @data = parse($_);
        my $line = $header . join('|', @data);
        # scalar <$input_fh> is almost certainly not doing what you expect, 
        # though I'm not sure what you're try to accomplish with it
        if ( $data[1] =~ /^I/ ) {
            print $OUTPUTA $line;
        } else {
            print $OUTPUTB $line;
        }
    }
}

sub parse {
    my $input = shift || return;
    my $input =~ s/"//g; # remove double quotes
    # Here I've combined the removal of trailing spaces with the split.
    my @fields = split( m{\s*\|}, $input );
    return @fields;
}