← Back to Perl Course | Chapter 4: Regular Expressions | Lesson 6 of 7

Substitution करना

s/pattern/replacement/ text ढूंढता है और इसे replace करता है।

In this page:

  1. Substitution

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

perl
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
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. /g भूल जाना और सिर्फ पहला match replace करना
  2. एक constant string पर s/// इस्तेमाल करने की कोशिश करना
  3. यह भूल जाना कि 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.