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

I am new to perl I want to know how I would get print my result

my $what = ram; /($what){3}/; print $what;

As you have seen above that it should print ramramram but its printing only ram. Please help me out.

Replies are listed 'Best First'.
Re: simple regular expression printing
by davido (Cardinal) on Jul 15, 2013 at 04:22 UTC

    You're misunderstanding what regular expressions do. What they do is detect whether a string satisfies the regular expression's criteria for a match. They don't morph one pattern into another through the magic of quantifiers. You might want the s/// operator:

    my $what = 'ram'; $what =~ s/(\Q$what\E)/$1$1$1/; print "$what\n";

    Dave

      Thanks Dave

Re: simple regular expression printing
by rjt (Curate) on Jul 15, 2013 at 05:10 UTC

    Have a look at perlretut:

    What is a regular expression? A regular expression is simply a string that describes a pattern. [...] In Perl, the patterns described by regular expressions are used to search strings, extract desired parts of strings, and to do search and replace operations.
     /($what){3}/;

    To have this expression operate on $what, you would need to write it $what =~ /($what){3}/;. But even then, it won't match, because it would try to match the contents of $what 3 times. In this case, you would be better off with the x operator. You probably also want to print a newline at the end:

    use 5.012; use warnings; my $what = 'ram' x 3; print $what, "\n";

    Or even...

    use 5.012; use warnings; say 'what' x 3;

    Your code should always use warnings;, and usestrict; or use5.012; (or later), which automatically enables 'strict'. You might usediagnostics as well. All of these will help you understand and avoid many errors.

Re: simple regular expression printing
by Laurent_R (Canon) on Jul 15, 2013 at 06:19 UTC

    As an additional comment to what has already been said, don't use bare words like this:

    my $what = ram;

    But rather use this:

    my $what = "ram";

    or:

    my $what = 'ram';

      Thanks Laurent..I will keep this thing in mind

Re: simple regular expression printing
by Anonymous Monk on Jul 15, 2013 at 06:51 UTC