kirk123 has asked for the wisdom of the Perl Monks concerning the following question:

Hi:

I code like the following but the second (.*) does'nt match the newline. How do I get it to matches everthing including a newline.

foreach (@lines) { if ( /(.*)$old_hostname(.*)/i ) { $concat = $1 . $new_hostname . $2; s/$_/$concat/g; } open (OUT,">$file"); print OUT @lines; }
--kirk

Edit by myocom: Added code tags and fixed formatting.

Replies are listed 'Best First'.
Re: How do you match for everything including newline
by fruiture (Curate) on Aug 22, 2002 at 19:28 UTC

    Use the /s modifier to make . match \n. See perlop for a full description.

    update: perlre contains the full description of the /imsx modifiers.

    --
    http://fruiture.de
Re: How do you match for everything including newline
by simon.proctor (Vicar) on Aug 22, 2002 at 19:31 UTC
    You need to look at perl re, specifically the s modifier:
    s Treat string as single line. That is, change ``.'' to match any character whatsoever, even a newline, which normally it would not match.
    I've taken your code and thrown a quick example together. This code isn't anything special but it works and hopefully will point you in the right direction
    use strict; use warnings 'all'; my @lines = ( "two three two twoone\ntwo four", "four five" ); my $old_hostname = 'two'; my $new_hostname = 'one'; my $new_file = 'filename.txt'; open(FH,'>',$new_file) || die $!; foreach my $line (@lines) { $line =~ s/(.*?)$old_hostname(.*?)/$1$new_hostname$2/sgi; print FH $line . "\n"; } close(FH);
    Which outputs:
    one three one oneone one four four five
    If you need to delimit the occurences more tightly then you'll need to modify the (.*?) constructs :).

    Please msg me if there are any fubars :)

    HTH

    Simon