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

Hi, I have a scenario to search and replace a string with alphanumeric characters with another string containing alphanumeric characters

Here's the code:
$fileName = $ARGV[0]; $OldVer="1.1.2.1-ABCD-PQ00.1.1.2.1.TAG"; $NewVer="1.1.2.2-ABCD-PQ01.1.1.2.2.TAG"; print "OldVersion :: $OldVer \n"; print "NewVersion :: $NewVer \n"; #Open Inputfile to read line by line data $file1 = $ARGV[0]; open(INPUTFILE,"<",$file1) || die "File to read could not be found. $! +"; # Create a .tmp file to copy search and replaced data $file2 = $ARGV[0].".tmp"; # Open output file in write mode open(OUTPUTFILE,">",$file2) || die "File to write could not be found. +$!"; print "Calling SearchAndReplace subroutine ... \n"; searchReplace(); sub searchReplace { # Read the input file line by line while (<INPUTFILE>) { $_ =~ s/$OldFPVer/$NewFPVer/; print OUTPUTFILE $_; } close INPUTFILE; close OUTPUTFILE; }

The inputs to this script would be provided as arguments i.e

 perl searchReplaceVer.pl 1.1.2.1 1.1.2.2

Replies are listed 'Best First'.
Re: Search/Replace action using "."
by Corion (Patriarch) on Sep 08, 2011 at 07:31 UTC

    Your value for $OldVer contains regular expression meta characters, like "." (which usually matches any character. See perlre for \Q...\E or quotemeta for how to make sure your value gets interpreted as value instead of a regular expression. You also want to make sure to replace more than just one version occurrence per line, I guess:

    s/$OldVer/$NewVer/g;
Re: Search/Replace action using "."
by ikegami (Patriarch) on Sep 08, 2011 at 07:32 UTC

    To create a regex pattern that matches a string of text, use quotemeta.

    my $OldVerPat = quotemeta($OldVer); s/$OldVerPat/$NewVer/

    quotemeta can be called via \Q..\E.

    s/\Q$OldVer\E/$NewVer/

    The \E can be ommitted since it's at the end of the pattern.

    s/\Q$OldVer\E/$NewVer/
Re: Search/Replace action using "."
by johngg (Canon) on Sep 08, 2011 at 09:47 UTC

    If you are simply incrementing the most minor part of the version you might be able to automate it a bit by capturing that part of the version number and incrementing it in the substitution using the 'e' flag to execute a bit of code.

    use strict; use warnings; use 5.010; my $rxSep = qr{[-_.]}; my @versions = qw{ 1.2.3.4 2.6 3_4_9 4-2-13-5 5 }; foreach my $version ( @versions ) { ( my $newVersion = $version ) =~ s{((?:\d+$rxSep)+)*(\d+)(?!$rxSep)} { my $ver = $2; ( defined $1 ? $1 : q{} ) . ++ $ver }e; say qq{$version => $newVersion}; }

    The output.

    1.2.3.4 => 1.2.3.5 2.6 => 2.7 3_4_9 => 3_4_10 4-2-13-5 => 4-2-13-6 5 => 6

    I hope this is helpful.

    Cheers,

    JohnGG