1

how can I get country from IP address in Perl? I have to use whois to do it. I know, that to take country I can use:

$test = `whois $ip |grep -i country`;

But it returns me "Country: DE". I need just "DE".

Jim Simson
  • 2,774
  • 3
  • 22
  • 30
Mateusz
  • 323
  • 2
  • 11
  • 23
  • 2
    The Country you're seeing isn't necessarily the "country from IP address". You should look into something like http://search.cpan.org/~maxmind/Geo-IP-1.45/lib/Geo/IP.pm instead. – bzlm Mar 30 '15 at 19:18
  • But I had to use whois :P In school my task is to use "whois" and get country from this. – Mateusz Mar 30 '15 at 19:20
  • Do not escape to the shell to do that, you have many whois libraries in Perl. – Patrick Mevzek Jan 02 '18 at 20:02

2 Answers2

1
my $country = `whois $ip | grep -Po '^Country:\s*\K.*';
chomp($country);

But seeing as the "P" in -P stands for "Perl", we might as well get rid of grep.

my $whois = `whois $ip`;
my ($country) = $whois =~ /^Country:\s*(.*)/m;
ikegami
  • 367,544
  • 15
  • 269
  • 518
0

I made it in little noob way, but it works xd

$test = `whois $_ |grep -i country`;
$rid = rindex($test, ":");
$b = substr("$test, $rid+1);

And now I have just "DE", "BR", "CN", "MX" etc :)

Mateusz
  • 323
  • 2
  • 11
  • 23