title: Use capture group variable entered on command line in Perl script
body: <p>My goal is to pass a capture group variable (i.e. $1) that was entered on the command line to my Perl script. </p>
  
  <p>To give you some background, I've created a script that takes a directory path, a pattern to search for and a replacement pattern. The script opens the directory, checks each file name to see if it matches the pattern and, if yes, changes the file name to be the replacement pattern. </p>
  
  <p>Here's an example of what I'm trying to accomplish.</p>
  
  <pre><code>my ($directory, $pattern, $replacement) = @ARGV;
  
  opendir DIR, $directory or die $!;
  
  foreach my $old (readdir DIR){
      my $new = s/$pattern/$replacement/ if(/$pattern/);      
      rename "$directory$old" =&gt; "$directory$new";
  }
  
  close DIR;
  </code></pre>
  
  <p>Imagine that that script is called as:</p>
  
  <pre><code>script.pl "/tmp/" ".*(\d+).*" "$1"
  </code></pre>
  
  <p>The idea is that all the files will be renamed to be just the numbers found in the file name. The problem is that $1 is getting mangled. If it's passed using double quotes it's interpolated at assignment and becomes nothing. If it's passed using single quotes, then it's treated as a literal and all the files will be called "$1". How can I get the files to be renamed to just the numbers found in their names? </p>