anjeline
anjeline

Reputation: 21

Get Multiple IP addresses from one variable using Perl to print a list

I need the script to print out the list of IP addresses line by line with the corresponding username and email address and the country. How do I get the multiple IP addresses to execute a command? I tried doing a loop but it only showed me one line of IP addresses. I would like my output to look like:

1 | login | [email protected] | 160.79.208.82 | United States
16 | login1 | [email protected] | 61.95.83.10 | Italy
23 | login2 | [email protected] | 81.48.63.93 | Australia
36 | login3 | [email protected] | 38.117.170.82 | Japan
51 | login4 | [email protected] | 2.233.30.85 | Mexico

Here is my code:

#!/usr/bin/perl -w
use lib '~/lib';
use strict;
use Net::IPInfoDB;

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

my $login = '1 | login | [email protected] | 160.79.208.82
            16 | login1 | [email protected] | 61.95.83.10 
            23 | login2 | [email protected] | 81.48.63.93 
            36 | login3 | [email protected] | 38.117.170.82 
            51 | login4 | [email protected] | 2.233.30.85';

$login =~ /(\d+\.\d+\.\d+\.\d+)/;

my $city = $g->get_city("$1");
my $addr = $g->get_country("$1");


printf "$login | (%s, %s)\n",
$city->city_name, $addr->country_name;

Upvotes: 1

Views: 1050

Answers (3)

ikegami
ikegami

Reputation: 386561

Use /g to find all matches.

my @ips = /(\d+\.\d+\.\d+\.\d+)/g;

That said, you obviously want the 4th field, so let's actually do that rather than risking getting something from the third field.

sub trim { my ($s) = @_; $s =~ s/^\s+//; $s =~ s/\s+\z//; $s }

for (split /^/m, $login) {
   chomp;
   my @fields = map trim($_), split /\|/;
   my $ip = $fields[2];
   ...
}

Upvotes: 1

NigoroJr
NigoroJr

Reputation: 1106

If you want to stick to not using the array, here's a solution to getting the IP addresses.

while ($login =~ m/(\d+\.\d+\.\d+\.\d+)/g) {
    print "$1\n";
}

Upvotes: 1

Davs
Davs

Reputation: 489

You are getting only one IP address, because it is exactly what you are doing by applying the regex ONCE on the whole $login.

#we split $login into an array, line-by-line
my @lines = split("\n",$login);
for my $line (@lines) {
    #now we iterate through every line one-by-one
    $line =~ /(?<ip>\d+\.\d+\.\d+\.\d+)/;

    print $+{"ip"}."\n";
}

Here we iterated through every line on $login and we applied the regex for each line individually..Instead of printing ofc you can do whatever you want with that ip.

Also I'm using here named match, which is only my preference, you don't have to use it.

Upvotes: 0

Related Questions