我是Perl脚本的初学者。下面的脚本用于检查文件修改时间是否大于600秒。我从阅读文件名filelist.txt
。
当我尝试打印文件修改时间时,它将修改时间显示为空白。
你能帮我哪里错了吗?
filelist.txt
a.sh
file.txt
#!/usr/bin/perl
my $filename = '/root/filelist.txt';
open(INFO, $filename) or die("Could not open file.");
foreach $eachfile (<INFO>) {
my $file="/root/$eachfile";
my $file_timestamp = (stat $file)[9];
my $timestamp = localtime($epoch_timestamp);
my $startTime = time();
my $fm = $startTime - $file_timestamp;
print "The file modified time is = $file_timestamp\n";
if ($rm > 600) {
print "$file modified time is greater than 600 seconds";
}
else {
print "$file modified time is less than 600 seconds\n";
}
}
你没有包含use strict;
或者use warnings;
是你的垮台。
你设置$fm
; 你测试$rm
。这些不是相同的变量。使用限制和警告可能会指出您的方式中的错误。专家会定期使用它们,以确保它们不会犯傻的错误。初学者也应该使用它们,以确保它们也不会犯傻的错误。
修改后的脚本:
use strict;
和use warnings;
my
$epoch_timestamp
或$timestamp
$info
)和的三个参数形式open
chomp
正在执行其工作/root
die
die
my $startTime = time;
循环进行优化码:
#!/usr/bin/perl
use strict;
use warnings;
my $filename = './filelist.txt';
open my $info, '<', $filename or die "Could not open file $filename";
foreach my $eachfile (<$info>)
{
chomp $eachfile;
my $file="./$eachfile";
print "[$file]\n";
my $file_timestamp = (stat $file)[9];
my $startTime = time();
my $fm = $startTime - $file_timestamp;
print "The file modified time is = $file_timestamp\n";
if ($fm > 600) {
print "$file modified time is greater than 600 seconds\n";
}
else {
print "$file modified time is less than 600 seconds\n";
}
}
close $info;
切线:如果您在工作/root
,则有可能以user身份运行root
。我相信您的备份很好。尝试编程root
非常危险。一个简单的错误可以消灭整个计算机,与仅以致命用户(而不是像上帝一样的超级用户)运行时相比,造成的损害要大得多。
强烈建议:不要学习以root身份编程!
如果您忽略此建议,请确保您具有良好的备份,并知道如何从中恢复。
(FWIW:我以非root用户身份运行Mac;甚至以非root用户身份运行系统升级。我偶尔会通过sudo
或等效方式使用root特权,但我从来没有以的身份登录root
。我不需要这样做。而且我将花费的时间root
减少到最小程度,将损坏的可能性降到最低。我已经在Unix系统上工作了30年;在过去的25年中,我从未发生过根特权事故,因为我很少从事根。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句