I'm trying to replace IP-Addresses with random numbers in Perl:
while (my $line = <file>){
$line =~ $regex{'ipadress'};
my $rand0 = int(rand(256));
my $rand1 = int(rand(256));
my $rand2 = int(rand(256));
my $rand3 = int(rand(256));
$& = "$rand0.$rand1.$rand2.$rand3\n";`
}
The problem is that in some cases there are multiple IP-Addresses in one line.
How to avoid that they all get the same random numbers?
Well for a start $&
is read-only and you can't assign to it like that to modify the target string.
I'm also unsure whether the key to your hash is really ipadress
(with one d
) but I'm sure you can fix it if not.
I would write something like this. The /e
modifier on the substitute operator causes the replacement string to be executed to determine what to replace the match with. The join
statement generates four byte values from 0 to 255 and joins them with dots to form a random address.
while (my $line = <$fh>) {
$line =~ s{$regex{ipadress}}{
join '.', map int(rand(256)), 0..3
}eg;
print $line;
}
This might be helpful:
sub rip { return join(".", map { int(rand(256)) } (1..4) ) }
open my $f, '<', 'input' or die($!);
while (my $line = <$f>){
$line =~ s/$regex{'ipadress'}/rip()/eg;
}
close($f);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With