Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^3: How to use Substr to bulk substitutions?

by Marshall (Canon)
on May 17, 2019 at 06:57 UTC ( [id://11100147]=note: print w/replies, xml ) Need Help??


in reply to Re^2: How to use Substr to bulk substitutions?
in thread How to use Substr to bulk substitutions?

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11100147]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-04-25 23:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found