2

你能告诉我如何使用这段代码创建一个子程序或函数吗?基本上我想把我的代码变成一个子程序,这样我就可以在不让我的脚本太长的情况下重复使用它。

这是我的脚本:

#!/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>;
    }
}     
4

1 回答 1

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;
}
于 2013-04-02T15:56:45.890 回答