如何提供默认输出

时间:2013-11-18 20:12:40

标签: arrays perl ip-address

如果查询没有返回任何结果,我正在尝试使用以下Perl程序来打印默认值。我不知道该怎么做。

当我运行脚本时,我收到错误:无法在未定义的值上调用方法“country_name”。如果没有返回结果,是否可以更改程序以打印默认值?

#!/usr/bin/perl update IP addresses with country
use strict;
use warnings;
use Net::IPInfoDB;

my $psql = "/usr/local/pgsql/current/bin/psql";
my $db = 'cpi';
my $args = "-U postgres -qc";

my $date = `/bin/date +\%y\%m\%d%H`;
my $reportfile = "/tmp/multiiplogins-$date";

my $sendmail = "/usr/sbin/sendmail -t -fcpi\@user.com";
my $mailsubject = "Login Report";
my $mailto = 'email@user.com';

my $query = "SELECT userid, login, email, logins, ips FROM (SELECT userid,login,email,      count(userid) AS logins, count(ipaddr) AS ips FROM (SELECT l.userid, u.login, u.email, l.ipaddr FROM synloginaccess l, synusers u$

my $query2 = "SELECT l.userid, login, email, ipaddr FROM synloginaccess l, synusers u where l.accesstime > (now() - interval '24 hours') and l.type=2 and l.userid=u.userid ORDER BY l.userid;";

open (REPORT, ">$reportfile");

my $command = qq/$psql $db $args "$query"/;
my $command2 = qq/$psql $db $args "$query2"/;

my $result = `$command`;
my $result2 = `$command2`;

my $g = Net::IPInfoDB->new;
$g->key("api_key");

#we split $login into an array, line-by-line
my @lines = split("\n", $result2);
for my $line (@lines) {
#now we iterate through every line one-by-one
if ($line =~ /(?<ip>\d+\.\d+\.\d+\.\d+)/) {
   my $city = $g->get_city("$1");
   my $addr = $g->get_country("$1");
   print "$line " . "| " . "\t" . $city->city_name . ", " . $addr->country_name ."\n";
   print REPORT "$line " . "| " . "\t" . $city->city_name . ", ". $addr->country_name ."\n";
 }
else {
   print "$line \n ";
     }
  }


close REPORT;
mailReport();

sub mailReport{
#mail it
open(MAIL, "|$sendmail");
print MAIL "To: $mailto\n";
print MAIL "Subject: $mailsubject\n";
print MAIL "\n";
open (INFILE, "$reportfile");
my @contents = <INFILE>;
my $line;`

1 个答案:

答案 0 :(得分:1)

$addr ? $addr->country_name : "default"