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

im a newbie and i want to replace https://abc.net/cm/one into https://abcde.net/dm/two in a text file im able to open and read the text file...for a single string im using $line =~ s/ABC/CDE/g; which works fine...but how do to the same for the path mentioned above..

Replies are listed 'Best First'.
Re: Replace Strings
by NetWallah (Canon) on Feb 14, 2012 at 05:53 UTC
    Assuming you want some flexibility about your substitutions, you can use something like this:
    use strict; use warnings; my @replace_by_level =( # Level 0 ---- { "abc.net" => "abcde.net", "something.else" => "Other.thing"}, # Level 1 --- { cm => "dm", dn => "xx", ef => "yy"}, # Level 2 -- { zero => "one", one => "two", two => "three"}, # Other levels as required ... ); my $orig_url = "https://abc.net/cm/one"; my ($transformed_url, $temp) = $orig_url =~m|(\w+://)(.+)|; my $level=0; $transformed_url .= join "/", map { $replace_by_level[$level++]{$_} } +split /\//, $temp; print qq|$transformed_url\n|; # https://abcde.net/dm/two
    Checking whether the transformation exists, before applying it is left as an exercise.

                “PHP is a minor evil perpetrated and created by incompetent amateurs, whereas Perl is a great and insidious evil perpetrated by skilled but perverted professionals.”
            ― Jon Ribbens

Re: Replace Strings
by kcott (Archbishop) on Feb 14, 2012 at 05:42 UTC

    Based on what you've provided, you can simply put your old and new URLs into variables and do the substitution the same way as you did with s/ABC/CDE/g. Here it is on the commandline:

    ken@ganymede: ~/tmp $ perl -Mstrict -Mwarnings -E ' > my $line = q{blah blah https://abc.net/cm/one blah blah}; > my $old_url = q{https://abc.net/cm/one}; > my $new_url = q{https://abcde.net/dm/two}; > $line =~ s/$old_url/$new_url/g; > say $line; > ' blah blah https://abcde.net/dm/two blah blah

    -- Ken