| Refresh | Home EGTry.com

lite string substitution without using pattern, case sensitive or not sensitive


case sensitive string replacement

 print subPart("rmi.port=1234", "1234", "500"), "\n";
 #output: rmi.port=500

 print subPart("rmi.port=1234", "1233", "600"), "\n";
 #not matched: return undef
 
#replace a substr to another,one instance
sub subPart {
  my ($line, $from, $to)=@_;
  my $pos=index($line, $from);
  if ($pos >-1) {
    $line=substr($line,0,$pos) . $to . substr($line, $pos+length($from));
    return $line;
  } 
  return undef;
}


case insensitive string replacement

print subPartI("rmi.port=1234", "Port=1234", "PORT=500");
#output: rmi.PORT=500

#replace a substr to another,one instance, case insensitive
sub subPartI {
  my ($line, $from, $to)=@_;
  my $pos=index(lc($line), lc($from));
  if ($pos >-1) {
    $line=substr($line,0,$pos) . $to . substr($line, $pos+length($from));
    return $line;
  } 
  return undef;
}