I am writing one of my first perl scripts and I need to create a new variable with the elements of an array. I need to take an IP address entered by a user and manipulate the last octet so it can be used in a router configuration. I am able to split the address into it's four octets. I can also make changes to the array elements as needed, but I can not reassemble the new address after I manipulate the octet I want. Here is my sample code:
Code:
#!/usr/bin/perl
# tests the use of ipcalc function in linux with matching
use strict;
use warnings;
my $ip_addr;
my $net;
my $mask;
my $cidr;
my $pe;
my $ce;
#my $nw_addr;
print "Enter IP address: e.g. 1.1.1.1/32\n";
$ip_addr = <>;
my @ipc_arr=`ipcalc -n -m -b -p $ip_addr`;
for(@ipc_arr){
chomp;
print $_ . "\n";
}
print "\n";
($net) = $ipc_arr[3] =~ m/=(.+)/;
print "The network is $net \n";
($mask) = $ipc_arr[0] =~ /=(.+)/;
print "\n";
print "The Subnet mask is $mask \n";
print "\n";
($cidr) = $ipc_arr[1] =~ /=(.+)/;
print "The CIDR notation is /$cidr \n";
print "\n";
print "You entered $net/$cidr which equals $net $mask\n";
#my @pe_arr = $net =~ /\.(\d+)$/ ; #only grabs last octet.
#my @pe_arr = $net =~ /(^\d+)\.(\d+)/ ; # returns first two octets
my @pe_arr = $net =~ /(^\d+)\.(\d+)\.(\d+)\.(\d+)/ ; # grabs all 4 octets!!!!!!!
for (@pe_arr){
print $_ . "\n";
($pe) = $pe_arr[3];
$pe = ($pe + 1);
chomp ($pe);
#my ($nw_addr) = ($pe_arr[0]"."$pe_arr[1]"."$pe_arr[2]"."$pe); #doesn't work
}
print "the last octect is $pe on the PE \n";
print "\n";
my ($nw_addr) = $pe_arr[0].$pe_arr[1].$pe_arr[2].$pe; #doesn't work
print"\n";
print $nw_addr "\n";
print "\n";
which yields the output:
Code:
Enter IP address: e.g. 1.1.1.1/32
67.54.99.136/29
NETMASK=255.255.255.248
PREFIX=29
BROADCAST=67.54.99.143
NETWORK=67.54.99.136
The network is 67.54.99.136
The Subnet mask is 255.255.255.248
The CIDR notation is /29
You entered 67.54.99.136/29 which equals 67.54.99.136 255.255.255.248
67
54
99
136
the last octect is 137 on the PE
Can't use string ("675499137") as a symbol ref while "strict refs" in use at ./ipcalc_test.pl line 47, <> line 1.
So, how can I assign $nw_addr with some of the first three elements of @pe_arr and the variable $pe? Additionally I get errors trying to add in the periods between the octets. The script fails and tells me "Scalar found where operator expected at...."
I have tried all kinds of combinations, but can not get the script to work.
Any help is appreciated.
thanks,
Robert