我正在尝试写入文件〜/ .log但文件仍为空.我不知道为什么会这样,一切似乎都很好.
我的系统是Ubuntu 9.10amd64,Perl 5.10.
#!/usr/bin/perl
# vim:set filetype=perl:
use strict;
use warnings;
use LWP::Simple qw||;
use Net::SMTP;
# Only because log file
$| = 1;
my $match_string = "... some text to match ..." ;
my $content;
my @mails = ('mejl1@provider1.com',
'mejl2@provider2.com',
);
my $data = <<END;
... Subject text ...
END
open(my $log, ">>","$ENV{HOME}/.log")
or die "Couldn't open log file";
sub get( $ ) {
my $content_ref = shift;
print {$log} "get: Error: $!\n"
until ( ${$content_ref}
= LWP::Simple::get("www.somesite.com/index.html") );
}
my $check_num = 0;
get( \$content );
while ( index($content, $match_string) != -1) {
print {$log} "Check number $check_num\n"
or die "Couldn't write in log file";
# This is printed
# print "Check number $check_num: $ENV{HOME}/.log\n";
$check_num++;
get( \$content );
sleep 60*30;
}
my $server = "smtp.my_provider.org";
my $smtp = Net::SMTP->new($server)
or print {$log} "smtp: Couldn't connect on $server\n";
$smtp->mail('my_mail@my_provider.org')
or print {$log} "smtp: Error in mail\n";
$smtp->bcc(@mails)
or print {$log} "smtp: Error in bcc\n";
$smtp->data();
$smtp->datasend($data)
or print {$log} "smtp: Error when sending data\n";
$smtp->dataend;
$smtp->quit();
Run Code Online (Sandbox Code Playgroud)
您需要调试脚本的每个步骤.你有:
print {$log} "get: Error: $!\n"
until ( ${$content_ref}
= LWP::Simple::get("www.somesite.com/index.html") );
Run Code Online (Sandbox Code Playgroud)
虽然你可能改变了你的问题的URL,但是写get的可能是返回undef.我不确定你为什么在until那里使用.你想在网站上线之前永远运行吗?检查所有内容的返回值,看看发生了什么.
我将脚本的大部分内容简化为:
while( 1 ) {
my $data = LWP::Simple::get("http://www.somesite.com/index.html");
print "got [$data]\n";
if( substr( ... ) > -1 ) { sleep 1800; next }
.... do error stuff here ...
}
Run Code Online (Sandbox Code Playgroud)
但是,不要睡30分钟,只需每30分钟从cron运行一次脚本.这样你就摆脱了循环:
my $data = LWP::Simple::get("http://www.somesite.com/index.html");
print "got [$data]\n";
exit if( substr( ... ) > -1 );
.... do error stuff here ...
Run Code Online (Sandbox Code Playgroud)
也许你不够耐心?我看到脚本在退出前等了3分钟.
请注意,这$|仅适用于当前选定的文件句柄,这意味着STDOUT在此处.
您可以为旧学校中的任何文件句柄设置它,复杂的方式:
{
my $old = select $log;
$| = 1;
select $old;
}
Run Code Online (Sandbox Code Playgroud)
或者,如果你的文件句柄是从一个特定的类下降 - 并且它可能是自动生成的句柄属于这个类 - 那么你可以使用这个autoflush方法,这对你来说要容易得多,但是在幕后做同样的事情:
$log->autoflush(1); # untested
Run Code Online (Sandbox Code Playgroud)
让我们希望后者有效.
请参见IO ::处理和文件句柄的autoflush-他们是相关的,但我不能确定其适用于这里.