if you want to use Perl, at least read up on Perl before attempting things like this. with Perl, there is no need to use shell commands like ls.
the ways you can read a directory includes using opendir() and readdir(), or even the while loop
eg while (<*.txt>) { .... }
why do you need sprint if you are just going to print out the files? by the way, its sprintf not sprint. if the results of ls and your perl script does not match, then its not correct . you just simply try to run the script and see.
if you want to sort by latest time last, (-rt) you can get the file time and file name in a hash, then sort the hash. perldoc -f sort for more info.
Your code has numerous problems. Maybe if you describe what you want to do it will be easier to help you than to try and guess by looking at your code.
You want to find all the files that match <*$tester*st*> (but where is $tester defined in your script?). Then what do you want to do? Print just the newest file or just the oldest file or what?
What i am trying to do here is to simply perform the following unix command.
To list those files which matches the terms *$tester*st* and grab the latest file and assign it to a variable name ST_file.
Can you help ?
set ST_file = `ls -rt *$tester*st*|tail -1`
Re-writing the code
#!/usr/local/bin/perl
#use strict;
use warnings;
use File::stat;
$[ = 1;
my $tester = "HP100";
my $TEMP = "/mydir/scripts";
my @file_match = (<*$tester*st*>);
for ( $count = 1 ; $count <= $#file_match ; $count++ ) {
open (FILE_MATCHED,"< $file_match[$count]");
open (LIST,">> $TEMP/list");
print LIST "$file_match[$count]\n";
my @STAT = stat(FILE_MATCHED);
push (my @time_stamp , $STAT[10]);
print LIST "$file_match[$count] $STAT[10]\n";
close (LIST);
close (FILE_MATCHED);
}
my @sorted = sort { $a <=> $b } my @time_stamp;
open (LIST, "< $TEMP/list");
while ( $line=<LIST> ) {
my @Fld = split(' ', $line);
print "$#sorted\n";
if ( $Fld[2] == $sorted[$#sorted] ) {
my $ST_file = sprintf{"%s",$Fld[1]};
}
};
close (LIST);
print "$ST_file\n";
I just a simpler code to simulate the unix command, but how am i suppose to assign the string being printed out to a variable ?
Tried to use the below but it can't work.
Can any expert help ?
open(F, " ls -rt *$tester*st* | tail -1 | ") or die;
while (<F>) {
my $ST_file = sprintf("%s",$_);
}
print "$ST_file\n";
Through Try and Error , i finally found out the way to do it.
Can any expert explain why with " while ($line=<F>) ", it is able to work ?
But with " while (<F>) " , it is not able to work ?
Correct Code:
open(F, " ls -rt *$tester*st* | tail -1 | ") or die;
while ($line=<F>) {
chomp;
my $ST_file = sprintf("%s",$line);
}
close(F);
print "$ST_file\n";
Wrong Code:
open(F, " ls -rt *$tester*st* | tail -1 | ") or die;
while (<F>) {
chomp;
my $ST_file = sprintf("%s",$_);
}
close(F);
print "$ST_file\n";