Perl Net::IP not working

Experts - I have a snippet of code I can't figure out. I was hoping someone could help me here.
I have a file of IPv6 address that I need to format correct.
Example in:

2620:0:2d0:200::7
2620:0:2d0:200:a0:c
2620:0a:3f0:200:a0:c

I need to convert them to:

2620:0000:02d0:0200:0000:0000:0000:0007
2620:0000:02d0:0200:00a0:0000:0000:000c
2620:000a:03f0:0200:00a0:0000:0000:000c

I'm reading the file into @tstIPs and then I'm trying to loop through them and update accordingly into @testIPs using Net::IP per below.

open(FH, "<", $fh) or die "Can't open file: $fh$!\n";
my @tstIPs=<FH>;
close(FH);

foreach my $i (@tstIPs) {
   my $tstip = new Net::IP ($i,6);
   push @testIPs, $tstip->ip();

}

I'm getting the following error:

Can't call method "ip" on an undefined value at ./dbi.pl line 43.

I can't figure out what's going on here and need help.

Thanks

Take a look at the highlighted in red comments. Check the return of new Net::IP before assuming that it created an object. Use Net::IP::Error().

Why does it fail?
It needs another : or it will be too ambiguous.

2620:0:2d0:200:a0::c
2620:0a:3f0:200:a0::c
2620:0000:02d0:0200:00a0:0000:0000:000c
2620:000a:03f0:0200:00a0:0000:0000:000c
1 Like

Thanks for the rapid reply.
How can I use the code you suggested below?

Net::IP::Error()

---------- Post updated at 01:18 AM ---------- Previous update was at 12:47 AM ----------

Okay. I think I got the error working to display.

It displaying:

Invalid IP address 2620:0:2d0:200:0:0:0:7

But it looks like a good IPv6 to me.

Yes it's a good one.

perl -e '
require Net::IP;
$str = "2620:0:2d0:200:0:0:0:7";
$ip = new Net::IP($str, 6);
print $ip->print, "\n";
'
2620:0:2d0:200::7/128
1 Like