PERL - getting last file using wild cards

Hi experts,
I am new to perl.
I am trying to get the last file from set of files.
Using the below code; but getting error
pls help

Files:

-rw-r--r--   1 abc    abc      12584 Mar 18 16:22 /abc/def/ghi/xyz.HOSTNAME.2016.03.18.16.21.69709-6
-rw-r--r--   1 abc    abc      12623 Mar 18 16:25 /abc/def/ghi/xyz.HOSTNAME.2016.03.18.16.24.69709-7
-rw-r--r--   1 abc    abc      12623 Mar 18 16:27 /abc/def/ghi/xyz.HOSTNAME.2016.03.18.16.26.69709-8

Code:

$file = `ls -1rt /abc/def/ghi/xyz.${`hostname`}.2???.??.??.??.??.* | tail -1` ;
chomp($outfile = $file) ;
 print "THE OUTFILE IS ......................... $outfile\n";

ERROR:

/abc/def/ghi/xyz.HOSTNAME: No such file or directory
sh: line 2: .2???.??.??.??.??.*: not found
THE OUTFILE IS .........................

try:

$file = `ls -1rt /abc/def/ghi/xyz.\$(hostname).2???.??.??.??.??.* | tail -1` ;
chomp($outfile = $file) ;
 print "THE OUTFILE IS ......................... $outfile\n";
1 Like
my $pattern = "/abc/def/ghi/xyz.$ENV{HOSTNAME}.2???.??.??.??.??.*";
my ($file) = qx{ls -t $pattern};
print "THE OUTFILE IS ......................... $file";
1 Like

A more perl-ish way:

my @files = glob "/abc/def/ghi/xyz.HOSTNAME.2016*";
my @sort_files = sort { -M $a <=> -M $b } @files;

print "The OUTFILE is ... $sort_files[-1]\n";

Wouldn't be $sort_files[0] ?

my ($files) = sort {-M $a <=> -M $b } glob "/abc/def/ghi/xyz.$ENV{HOSTNAME}.2???.??.??.??.??.*";
print "THE OUTFILE IS ......................... $file";