Substitution करना
s/pattern/replacement/ text ढूंढता है और इसे replace करता है।
In this page:
Substitution
s/// operator उस string को बदलता है जिससे यह bound है और किए गए replacements की संख्या return करता है। हर match replace करने के लिए /g add करें, case ignore करने के लिए /i, और original बदलने की बजाय नई string return करने के लिए /r। /e के साथ replacement part Perl code की तरह evaluate होता है, इसलिए आप नया text calculate कर सकते हैं।
Note:
एक expression में एक copy transform करने के लिए /r इस्तेमाल करें, जैसे print $text =~ s/a/b/gr।
उदाहरण: Substitution
use strict;
use warnings;
my $text = "I like cats. Cats are great; my cat is grey.";
(my $copy = $text) =~ s/cat/dog/;
print "first only: $copy\n";
my $n = ($copy = $text) =~ s/cat/dog/gi;
print "all, ignoring case ($n): $copy\n";
print "with /r: ", $text =~ s/great/wonderful/r, "\n";
print "original kept: $text\n";
my $prices = "apple 3, pear 5";
$prices =~ s/(\d+)/$1 * 2/ge;
print "doubled: $prices\n";
my $swap = "Smith, John";
$swap =~ s/(\w+), (\w+)/$2 $1/;
print "swapped: $swap\n";
# Output:
# first only: I like dogs. Cats are great; my cat is grey.
# all, ignoring case (3): I like dogs. dogs are great; my dog is grey.
# with /r: I like cats. Cats are wonderful; my cat is grey.
# original kept: I like cats. Cats are great; my cat is grey.
# doubled: apple 6, pear 10
# swapped: John Smith
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- /g भूल जाना और सिर्फ पहला match replace करना
- एक constant string पर s/// इस्तेमाल करने की कोशिश करना
- यह भूल जाना कि s/// variable modify करता है जब तक /r इस्तेमाल न हो
चैप्टर सारांश
- s/old/new/ पहला match replace करता है
- /g सारे matches replace करता है
- /r एक modified copy return करता है
- /e replacement को code की तरह evaluate करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: