need to replace one segment of an IP

K

kreiss

for an admin script, I would like to replace the fourth octet of
an IP, ie: 192.168.0.10 would become 192.168.0.20.

there must be an easy way to do this with a scalar that I am just too
dense to find myself. any help would be appreciated.
 
S

Scott W Gifford

kreiss said:
for an admin script, I would like to replace the fourth octet of
an IP, ie: 192.168.0.10 would become 192.168.0.20.

there must be an easy way to do this with a scalar that I am just too
dense to find myself. any help would be appreciated.

If you have the IP address as a string in $ip and the last octet in a
variable called $hostnum, you could simply do

$ip =~ s/\d+$/$hostnum/;

-----ScottG.
 
B

Brian McCauley

kreiss said:
for an admin script, I would like to replace the fourth octet of
an IP, ie: 192.168.0.10 would become 192.168.0.20.

there must be an easy way to do this with a scalar that I am just too
dense to find myself. any help would be appreciated.

Your problem is that you've not analysed your problem. The description
you've given is totally inadequate for anyone to figure out what you
actually want to do. Before you can implement anything in any language
you need first to be able to describe what it is you want to do.

Random shot in the dark: You want to add 10 to the last element any
dotted quad in a string.

s/(\d+\.\d+\.\d+\.)(\d+)/$1.($2+10)/eg;

I've assumed here that we don't care what happen to longer dotted
sequences of digits.
 
M

Matt Garrish

kreiss said:
for an admin script, I would like to replace the fourth octet of
an IP, ie: 192.168.0.10 would become 192.168.0.20.

In addition to the regex approaches already provided, you can also split and
recombine to manipulate the parts (although far more work than needed in
this case):

my $ip = '192.168.0.10';

my @octet = split(/\./, $ip);

# whatever quick and dirty manipulation/checks
$octet[3] = '20';

$ip = join('.', @octet);

Matt
 
K

kreiss

If you have the IP address as a string in $ip and the last octet in a
variable called $hostnum, you could simply do

$ip =~ s/\d+$/$hostnum/;

-----ScottG.
that is great, thannks to all who *helped*.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top