Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

eval and if problem 1

Status
Not open for further replies.

kodr

Programmer
Dec 4, 2003
368
0
0
Help. I've got two versions of my code. The first one works as long as the remote server is reachable and fails (obviously) when the remote server is unreachable.

My second version is my attempt to capture the error and populate some error text.

Code:
$mechanize->get($url);
my $page = $mechanize->content;

Code:
eval {$mechanize->get($url);};
if ($@) {
        my $page = "Could not reach the Chicago Server!";
}
else {
        # Assign the page content to $page
        my $page = $mechanize->content;
}
 
You're using Look into the success() or is_success() function/method in the documentation insterad of using eval.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Thanks, I don't know how I missed that.
 
After much head scratching and searching, here's the solution I ended up with:

Code:
#!/usr/bin/perl
require Net::SMTP;
Net::SMTP->import;

# Include the [URL unfurl="true"]WWW::Mechanize[/URL] module
use [URL unfurl="true"]WWW::Mechanize;[/URL]
#New
#use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request::Common qw(GET);
use HTTP::Cookies;

my $ua = LWP::UserAgent->new;
$ua->agent('Mozilla/80');
$ua->cookie_jar(
	HTTP::Cookies->new(
		file => 'mycookies.txt',
		autosave => 1
	)
);

my $req = GET '[URL unfurl="true"]http://xxx.xxx.xxx.xxx/server_status.php';[/URL]
my $res = $ua->request($req);
if ($res->is_success) {
	$page = $res->content;
} 
else {
	$page = "Error: Could not reach Server 1!";
}

$req = GET '[URL unfurl="true"]http://xxx.xxx.xxx.xxx/server_status.php';[/URL]
$res = $ua->request($req);
if ($res->is_success) {
	$page2 = $res->content;
}
else {
	$page2 = "Error: Could not reach Server 2!";
}
# You need to fill in the variables.
# Read the perldoc for more info on using SMTP.

my $smtp = Net::SMTP->new('xxx.xxx.xxx.xxx') or die $!;
$smtp->mail( 'xxxxxx@xxxxx.com' );
$smtp->to( 'xxxxx@xxxxxxxx.com' );
$smtp->data();
$smtp->datasend("To: xxxx\n");
$smtp->datasend("From: xxxxx\n");
$smtp->datasend("Subject: Server Status\n");
$smtp->datasend("\n"); # done with header
$smtp->datasend($page."\n".$page2);
$smtp->dataend();
$smtp->quit(); # all done. message sent.

server_status.php is just a php page that executes a small script file and returns some data.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top