用于访问perl的多个数组元素的子例程

时间:2015-04-02 22:34:49

标签: arrays perl subroutine

我正在尝试在多个数组元素上运行一个sub。

while (my $line = <DATA>) {
    my @lines = split(/\t/, $line); # everything
    my @dates = ($lines[0]); # <- I would like to add all date fields into here.
    $lines[0] = date($dates[0]);
#   $lines[0] = date($lines[0]);
#   $lines[0] = date($lines[2]);
#   $lines[0] = date($lines[3]);
#   $lines[0] = date($lines[4]);
#   $lines[0] = date($lines[5]);
    sub date {
        my ($m, $d, $y) = split /[-\/]/, $lines[0]; # <- this is where I want to  access both $lines[0] through $lines[5], or it could be hundreds of fields.

        if ($m =~ /^[0-9]$/) {
            $m = "0".$m;
        }
        if ($d =~ /^[0-9]$/) {
            $d = "0".$d;
        }
        if ($y =~ /^[2-9]\d$/) {
            $y = $y+1900;
        }
        elsif ($y =~ /^[0-1]\d$/) {
            $y = $y+2000;
        }

        $dates[0] = join "-", ($y, $m, $d); # <-this is where I want to reformat all of my date fields.
    }

    print join ",", @lines;
}

__DATA__
12-02-2004  hello   12-09-98    12-2-04 1-01-15 12/2/12
12-02-2004  hello   12-09-98    12-2-04 1-01-15 12/2/12
12-02-2004  hello   12-09-98    12-2-04 1-01-15 12/2/12
12-02-2004  hello   12-09-98    12-2-04 1-01-15 12/2/12

在这段代码中,我只能重新格式化我选择的一个日期字段,并且我想重新格式化所有字段。是否有任何建议和提示可以帮助我解决这个问题?

我希望所有其他日期格式化,而不是仅仅格式化我指定的第一个日期字段。

1 个答案:

答案 0 :(得分:0)

使用sprintf格式化数字。

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

sub format_date {
    my $date = shift;
    if (my ($m, $d, $y) = /([0-9]+).*?([0-9]+).*?([0-9]+)/) {
        $y += 1900 if $y < 1900;
        $y += 100  if $y < 1920;
        $date = sprintf '%4d-%02d-%02d', $y, $m, $d;
    }
    return $date
}


while (<DATA>) {
    my @fields = split;
    $_ = format_date($_) for @fields;
    say join ', ', @fields;
}

__DATA__
12-02-2004  hello   12-09-98    12-2-04 1-01-15 12/2/12
12-02-2004  hello   12-09-98    12-2-04 1-01-15 12/2/12
12-02-2004  hello   12-09-98    12-2-04 1-01-15 12/2/12
12-02-2004  hello   12-09-98    12-2-04 1-01-15 12/2/12