nvlung has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I'm so confused when reading the code below:
$new_msg =~ s/<c>/$count/g; $new_msg =~ s/<p>/$pcnt/g; $new_msg =~ s/<t>/$total/g;
Could you please explain what these char "~ s/<c>/" use for? what value $new_msg will get here? Thanks so much!

Replies are listed 'Best First'.
Re: declare a variable in perl
by Athanasius (Archbishop) on Jan 03, 2014 at 08:38 UTC

    Hello nvlung, and welcome to the Monastery!

    LanX and choroba have answered your question, but a little code may help to make things clearer:

    #! perl use strict; use warnings; my $new_msg = 'I have <c> apples, <p> pineapples, and <t> pieces of fruit. Yes, I do have <c> apples!'; my $count = 7; my $pcnt = 5; my $total = $count + $pcnt; print "\nBefore applying the substitutions, \$new_msg is:\n$new_msg\n" +; $new_msg =~ s/<c>/$count/g; $new_msg =~ s/<p>/$pcnt/g; $new_msg =~ s/<t>/$total/g; print "\nAfter applying the substitutions, \$new_msg is now:\n$new_msg +\n";

    Output:

    18:30 >perl 820_SoPW.pl Before applying the substitutions, $new_msg is: I have <c> apples, <p> pineapples, and <t> pieces of fruit. Yes, I do have <c> apples! After applying the substitutions, $new_msg is now: I have 7 apples, 5 pineapples, and 12 pieces of fruit. Yes, I do have 7 apples! 18:30 >

    Note that the /g modifier on the substitutions “specifies global pattern matching--that is, matching as many times as possible within the string.” (perlop) If you remove the /g from the first substitution, only the first occurrence of <c> will be substituted.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Thanks Athanasius, It's very useful
Re: declare a variable in perl
by choroba (Cardinal) on Jan 03, 2014 at 07:58 UTC
    =~ is the binding operator. See perlop for details. It binds the left hand side to a pattern match or replacement. In this particular example, all <c>'s will be replaced by the value of $count, etc.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Thanks choroba!
Re: declare a variable in perl
by LanX (Saint) on Jan 03, 2014 at 07:57 UTC
      Thanks LanX! I'm reading :))