I need help please, my $inputfile
changes on daily basis which gets generated and store under /tmp
directory. File format date as follows.
/tmp
570572 Sep 13 21:02 sessions_record_2021-09-13_210052.csv
570788 Sep 14 09:01 sessions_record_2021-09-14_090041.csv
I'm not sure how to pick it up as an input file instead of hardcoded in my script
#!/usr/bin/perl
use strict; use warnings;
use Tie::Array::CSV;
use Data::Dumper;
use Date::Parse;
use POSIX qw(strftime);
my $hours = 1;
my $timenow = time;
my $inputfile = "sessions_record_2021-09-14_090041.csv";
tie my @sessions_record, 'Tie::Array::CSV', $inputfile, {
tie_file => { recsep => "\r\n" },
text_csv => { binary => 1 }
};
tie my @incidentidlist, 'Tie::Array::CSV', 'incidentidlist.csv';
@incidentidlist = map {
([$$_[4] =~ /\A([^\s] )/, $$_[4], $$_[18], ($timenow -
str2time($$_[18])) / 60 / 60])
} grep {
$$_[0] =~ /^ServiceINC/ && ($timenow - str2time($$_[18])) / 60 / 60 > $hours
} @sessions_record;
CodePudding user response:
Perl sort function on glob will produce sorted array and you interested in last element which can be addressed with index -1
.
use strict;
use warnings;
use feature 'say';
my $in_file = (sort glob('/tmp/sessions_record_*.csv'))[-1];
say $in_file;
If you interested in today's file localtime can be an assistance to form a filename $fname
.
use strict;
use warnings;
use feature 'say';
my($mask,$fname);
my($mday,$mon,$year) = (localtime)[3..5];
$year = 1900;
$mon = 1;
$mask = sprintf('/tmp/sessions_record_M-d-d_*.csv', $year, $mon, $mday);
$fname = (glob($mask))[0];
say 'File: ' . $fname;
say '-' x 45;
open my $fh, '<', $fname
or die "Couldn't open $fname";
print while <$fh>;
close $fh;
CodePudding user response:
You can use opendir
to open a directory and readdir
to read it. For each file accessed you can check if it has the correct format (as per simbabque's comment) and add it to an array.
Then you can sort your array.
Due to the naming convention the latest file will always sort as the 'largest' value in your sort.
You can red more about sorting (if you need to) at https://www.perltutorial.org/perl-sort/