Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguish multiple regex hits in a line?

Tags:

regex

perl

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?

like image 362
hcrudolph Avatar asked Jan 11 '23 17:01

hcrudolph


2 Answers

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;
}
like image 56
Borodin Avatar answered Jan 22 '23 10:01

Borodin


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);
like image 33
perreal Avatar answered Jan 22 '23 10:01

perreal