in reply to How to use Substr to bulk substitutions?

In general, using Perl regex is much better than running substr() multiple times on a single expression.
Where are you using substr()?
My version of Perl does not allow:
my $capture1 = $string, 6, 2, "is stretched";
#!/usr/bin/perl use strict; use warnings; my $string = 'This is string'; my $capture1 = $string, 6, 2, "is stretched"; # This will substitute a +s expected my $capture2 = $string, 9, 6, 'STRING'; # Now here original string wil +l be updated and positions I have already are of no use. __END__ Useless use of a constant (6) in void context at C:\test.pl line 6. Useless use of a constant (2) in void context at C:\test.pl line 6. Useless use of a constant ("is stretched") in void context at C:\test. +pl line 6. Useless use of a constant (9) in void context at C:\test.pl line 7. Useless use of a constant (6) in void context at C:test.pl line 7. Useless use of a constant ("STRING") in void context at C:\test.pl lin +e 7. Process completed successfully

Replies are listed 'Best First'.
Re^2: How to use Substr to bulk substitutions?
by phoenix007 (Sexton) on May 17, 2019 at 04:42 UTC

    That was typo now I have corrected it

      Updated code:
      #!/usr/bin/perl use strict; use warnings; my $string = 'This is string'; my $capture1 = substr $string, 6, 2, "is stretched"; # This will subst +itute as expected # REALLY? print $string,"\n"; # I get: # "This iis stretchedstring" # perhaps better is: my $string2 = 'This is string'; $string2 =~ s/string/streched string/; print "$string2\n"; # that prints: # "This is streched string" # Your second substr(): substr $string, 9, 6, 'STRING'; print $string,"\n"; # that prints: # This iis STRINGhedstring # I suspect that you want: $string2 =~ s/string/STRING/; print "$string2\n"; # that prints: # "This is streched STRING"
      Perl is wonderful with what are called "regular expressions" or regex'es. In general, use the power of the Perl language. substr() is a low level thing that can be used, but is very, very rare in Perl programs. substr() is very common in C programs because there is not a "built in regex" operator.

      To summarize:

      #!/usr/bin/perl use strict; use warnings; my $string = "This is string"; print "$string\n"; $string =~ s/string/stretched string/; $string =~ s/string/STRING/; print "$string\n"; __END__ This is string This is stretched STRING