Distinguish multiple regular expressions in a string?

I am 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 several IP addresses on the same line.
How to avoid the fact that they all get the same random numbers?

+4
source share
3 answers

Good for starters $&is read-only, and you can't assign it to that to change the target line.

I'm also not sure if the key to your hash is really ipadress(with one d), but I'm sure you can fix it if not.

- . /e , , . join 0 255 .

while (my $line = <$fh>) {
  $line =~ s{$regex{ipadress}}{
    join '.', map int(rand(256)), 0..3
  }eg;
  print $line;
}
+4

:

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);
+4

- IP-. : " , ?" , " IP- " ", IP- ".

: rand(256) 32 , , , , , , . @perreal:

sub rip {
    my $picked_addrs = shift;
    my $new_addr;
    do {
        $new_addr = join(".", map { int(rand(256)) } (1..4) );
    } while defined($picked_addrs->{$new_addr});
    $picked_addrs->{$new_addr} = 1;
    return $new_addr;
} 

open my $f, '<', 'input' or die($!);
while (my $line = <$f>){
    my %picked_addrs;
    $line =~ s/$regex{'ipadress'}/rip(\%picked_addrs)/eg;
}
close($f);

, , %picked_addrs while, reset :

open my $f, '<', 'input' or die($!);
my %picked_addrs;
while (my $line = <$f>){
    $line =~ s/$regex{'ipadress'}/rip(\%picked_addrs)/eg;
}
close($f);
+1

All Articles