Re: howto replace part of a string
by jeffa (Bishop) on Jun 14, 2006 at 14:37 UTC
|
jeanluca, we can better serve you if you tell us why you want to do this. Perhaps substr is the better solution, perhaps a regex is. Perhaps just plain old concatenation is the answer. Won't you take a little time to tell us why you need to do what you need to do instead of how to solve what you think you need to solve? Thanks.
| [reply] |
Re: howto replace part of a string
by japhy (Canon) on Jun 14, 2006 at 14:52 UTC
|
If you know the exact offsets in the string you want to replace, then substr() is definitely the way to go. Read its documentation, try it out, and post here again if you need further assistance.
| [reply] |
Re: howto replace part of a string
by Zaxo (Archbishop) on Jun 14, 2006 at 15:02 UTC
|
First pad out or trim the replacement text to 10 characters with pack,
$repl = pack 'A10', $repl;
then do the replacement with substr,
substr $str, 10, 10, $repl;
or,
substr($str, 10, 10) = $repl;
Thare are dozens of other ways to do it, and you don't need to pad or trim if that's not what you want.
| [reply] [d/l] [select] |
Re: howto replace part of a string
by MonkE (Hermit) on Jun 14, 2006 at 15:06 UTC
|
As others have said: use substr(). But I offer this additional advice: use substr() as an lvalue like so ...
$a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
# (remember perl strings start at position 0)
substr($a,9,11) = "0123456789-";
print "\$a='$a'\n";
| [reply] [d/l] |
Re: howto replace part of a string
by jeanluca (Deacon) on Jun 14, 2006 at 15:17 UTC
|
So, using substr as an lvalue worked (so my problem is solved :)
But I still don't understand why the following example doesn't work: $a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ;
($a = $a ) =~ s/^\S{5}(\S{4})\S+/\1xxxx/ ;
any suggestions ?
LuCa | [reply] [d/l] |
|
Well, for starters, you're using 5, 4, and *, rather than 10 and 20. Secondly, you're ignoring the warning message:
\1 better written as $1 at ./z.pl line 7.
(You are using strict and warnings, right?) Third - what's with the ($a = $a )? Finally, you've inverted the problem. You're replacing everything except characters 6 through 9. You probably want something like:
$a =~ s/^(\S{5})\S{4}/$1xxxx/;
Or, potentially simpler:
$a =~ s/(?<=^\S{5})\S{4}/xxxx/;
But what you really want is still substr. | [reply] [d/l] [select] |
|
So, now I understand what I was doing (or not doing). I never understood the \1, and I don't know why I do ( $a = $a ) too, I think I once copied it from somewhere without understanding it
Thanks a lot Luca
| [reply] |
|
Is this what you're trying to do?
$a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$a =~ s/^\S{5}(\S{4})\S+/$1xxxx/ ;
-imran | [reply] [d/l] |
|
You're right, but I realize now, because I didn't understand the expression, that it is not what I want!
| [reply] |
A reply falls below the community's threshold of quality. You may see it by logging in. |