Niko top-posts:
[ please don't top-post ]
"J. Gleixner" <
[email protected]> wrote in message
Niko said:
i need help replacing string in the middle of line like this :
var1:string:yyy:zzz:kkk.....:ggg
I'm guessing you want to replace 'string', in your example line above,
with another value and you know the beginning of the line you want to
replace, which in this case is 'var1'.
my $str = 'var1:string:abcd:edfg';
my $beg = 'var1';
my $new_string = 'new_value1';
$str =~ s/^$beg
[^:]*)/$beg:$new_string/;
for now this was my code :
### Find and replace strings in a file
sub Find_Rep {
my $PAT_TXT = $_[0];
It is more ideomatic (and faster) to say:
my $PAT_TXT = shift;
or
my ($PAT_TXT) = @_;
open (FILE,$S_FILE);
open (TEMPF,"> $T_FILE");
You should always, yes always, check the return value from open(). In
quick-and-dirty program it is sufficient to append "or die $!".
You should generally avoid using shared variables to pass arguments to
subrouitnes unless there is a special reason why it's justified.
If you use a bare file handle, FILE, in a subroutine you should use
local(*FILE). Better would be to use lexical file handles (unless you
need compatability with old Perls).
while (<FILE>) {
eval $PAT_TXT;
You should usually check the value of $@ after eval. If you can't think
of something more appropriate just re-throw with:
die $@ if $@;
But you shouldn't be using eval at all anyhow - you should be calling a
precomplied code entity - see below.
print TEMPF $_;
<STDIN>;
}
close (TEMPF);
close (FILE);
I think you have a missing closing curly.
####
$S_FILE="source file";
$T_FILE="target file";
$str1="var1";
str2="var2";
This is an error.
my $PAT_ST = 's/^$str1
[^:]*)/$str1:$str2/';
Find_Rep($PAT_ST);
You should use the natural representation for things (i.e. use a CODE
entity not a string for holding code).
You should use the natural name for things (i.e. don't use 'PAT' for the
name of a variable containing a substition command).
The capture brackets are redunant.
It would be a good idea to habitually put tThe $str1 on the LHS of the
s/// in \Q\E just in case it ever contains RE-special punctuation.
It would be more conventional to preserve the unchanged bit using a
capture rather the repeat it on each side of the s///.
my $substitution = sub { s/^(\Q$str1\E
[^:]*/$1$str2/ };