htmlregexcsvperlopendir

my input file date format changes on daily basis


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;

Solution

  • 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_%4d-%02d-%02d_*.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;