我正在使用 Perl 并有一個輸入檔案,其中包含多個日期,例如 17/04/2021 以文本形式寫入其中。我怎樣才能將它們轉換為日期格式,然后比較它們以查看哪個是最新的?
輸入檔案格式:
01/09/2020
23/10/2019
12/06/2022
15/08/2017
Perl 腳本:
#! /usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
my $InputFile = "path/to/file.input";
open(FH, '<', $InputFile) or die $!;
while(my $Line = <FH>)
{
}
close(FH);
謝謝。
uj5u.com熱心網友回復:
strftime(永遠)是你的朋友:
#!/usr/bin/env perl
# Sort timestamps
use 5.12.10;
use Time::Piece;
my $fmt='%d/%m/%Y';
my @t;
while( <DATA> ){
chop; # Delete newline
eval { push @t, Time::Piece->strptime($_, $fmt) } or say "Unexpected input: $_";
}
say $_->strftime($fmt) foreach sort @t;
__DATA__
01/09/2020
23/10/2019
12/06/2022
15/08/2017
uj5u.com熱心網友回復:
格式中的日期yyyymmdd可以直接、數字或詞法比較。所以轉過來
use warnings;
use strict;
use feature 'say';
# use List::Util qw(max);
my @dates;
while (<>) {
chomp;
push @dates, join '', reverse split '/';
}
@dates = sort { $a <=> $b } @dates; # latest: $dates[-1]
say for @dates;
# Or, if only the last one is needed (uncomment 'use' statement)
# my $latest_date = max @dates;
當在標量背景關系中使用時, “鉆石運算子”<>會逐行讀取在命令列上提交的檔案。為方便起見,分隔符的split引數仍然是正則運算式,即使我使用分隔符而不是. (默認情況下,它的另一個引數是variable。)還可以根據需要查看
reverse、
join、
sort和List::Util。''/\//$_
也可以在命令列程式(“單線”)中完成
perl -wnlE'push @d, join "", reverse split "/"; }{ say for sort @d' file
where}{代表END { }塊的開始。或者
perl -MList::Util=max -wnlE'... }{ say max @d' file
如果你想要更緊湊,
use warnings;
use strict;
use feature 'say';
say for sort map { chomp; join '', reverse split '/' } <>;
串列背景關系中的相同菱形運算子一次回傳所有行。
或者在命令列上
perl -wE'say for sort map { chomp; join "", reverse split "/" } <>' file
uj5u.com熱心網友回復:
這是一種方法:
#! /usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
use Time::Local;
my $InputFile = $ARGV[0];
open(my $fh, '<', $InputFile) or die $!;
## A hash to hold the times so we can sort later
my %seconds;
while(my $Line = <$fh>){
chomp($Line);
my ($day, $month, $year) = split(/\//, $Line);
my $secondsSinceTheEpoch = timelocal(0, 0, 0, $day, $month-1, $year);
$seconds{$secondsSinceTheEpoch}
}
close($fh);
my @sortedSeconds = sort {$a <=> $b} keys(%seconds);
print "$sortedSeconds[0]\n";
或者,如果你對整個簡潔的事情感興趣:
#! /usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
use Time::Local;
## A hash to hold the times so we can sort later
my %seconds;
while(<>){
chomp();
my ($day, $month, $year) = split(/\//);
$seconds{timelocal(0, 0, 0, $day, $month-1, $year)}
}
my @sortedSeconds = sort {$a <=> $b} keys(%seconds);
print "$sortedSeconds[0]\n";
在這兩種情況下,您都需要將檔案作為引數傳遞給腳本:
$ foo.pl file
1502744400
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/513173.html
標籤:linuxperl
