in reply to declare a variable in perl

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,

Replies are listed 'Best First'.
Re^2: declare a variable in perl
by nvlung (Initiate) on Jan 03, 2014 at 10:14 UTC
    Thanks Athanasius, It's very useful