title: How to replace matched pattern in perl
body: <p>I'm trying to write a Perl program that accepts an input pattern and print the string with the matched part enclosed with parentheses. For example, if I input the regex ".p" and the string is "developing", it should print "devel(op)ing"</p>
  
  <p>Here is my program:</p>
  
  <pre><code>if (/($pattern)/) {
      $_ =~ s/$1/($1)/;
      print;
  } else {
      print "no match\n";
  }
  </code></pre>
  
  <p>When I run it, I got the error message: </p>
  
  <blockquote>
    <p>Use of uninitialized value $1 in concatenation (.) or string at q1.pl
    line 12, &lt;> line 1.</p>
  </blockquote>
  
  <p>The string "devel()ing" was returned.
  I did some research and seems like the $1 is uninitialized because the string is not matched, but in my case, the $1 should always be initialized since I checked with "if...else..." </p>