in reply to Return to original loop

<DATA> exhausts the file handle in the first iteration and returns undef in all the following. Either store its content to an array, or use tell/seek to move back to the beginning of the handle.

BTW, don't use for with <>, use while. Also, use \Q$ip\E to treat the dots literally.

chomp(my @data = <DATA>); while (my $confLine = <$in>) { if ($confLine =~ /ip4-address address="/) { # No need to backslash + ". for my $ip (@data) { if ($confLine =~ /ip4-address address="\Q$ip/) { $confLine =~ s{/>}{update"/>}; } } } print {$out} $confLine; }

Or

my $data_start = tell DATA; while (my $confLine = <$in>) { if ($confLine =~ /ip4-address address="/) { # No need to backslash + ". seek DATA, $data_start, 0; while (my $ip = <DATA>) { chomp $ip; if ($confLine =~ /ip4-address address="\Q$ip/) { $confLine =~ s{/>}{update"/>}; } } } print {$out} $confLine; }

Update: quotemeta added.

لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: Return to original loop
by stroke (Acolyte) on Oct 15, 2015 at 14:19 UTC

    Thanks, I put the DATA contents into an array and it worked perfectly.

    One question on the quotemeta bit. The code snippet included:

     if ($confLine =~ /ip4-address address="\Q$ip/) {

    Should that be

     if ($confLine =~ /ip4-address address="\Q$ip\E/) {

    Or does it not matter, as the variable was the last thing in the regex? i had to tweak my regex and add a quote at the end, as it was matching incorrectly (i.e. 1.2.3.1 would also match 1.2.3.11, .12, etc.), so have gone with:

     if ($confLine =~ /ip4-address address="\Q$ip\E"/) {

      Hello stroke,

      See the section “Escape sequences” in perlre#Regular-Expressions, where \Q is defined as follows:

      \Q          quote (disable) pattern metacharacters until \E

      So you need the \E only when what follows contains metacharacters which are meant to behave as metacharacters. A double quote character " is not a metacharacter, so in this case adding the \E makes no difference.

      Nevertheless, it’s probably good practice to add it, to make the regex clearer and to guard against bugs in the event that the regex is extended in the future.

      See also quotemeta and perlrebackslash.

      Hope that helps,

      Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

        Thank you. It worked with/without, but I've left it in to future-proof the regex ! Thank you.