title: How can I execute Perl code stored inside a shell script variable?
body: <p>I've got a script that calls Perl's Time::HiRes module to calculate elapsed time. Basically the script gets the time by passing the following one-liner:</p>
  <pre><code>use Time::HiRes qw(time); print time
  </code></pre>
  <p>to the Perl interpreter via backticks and gets back the results.</p>
  <pre><code>#/bin/sh
  
  START_TIME=`perl -e 'use Time::HiRes qw(time); print time'`
  END_TIME=`perl -e 'use Time::HiRes qw(time); print time'`
  ELAPSED_TIME=$(echo &quot;($END_TIME - $START_TIME)&quot; | bc)
  echo $ELAPSED_TIME
  </code></pre>
  <p>I tried to rewrite it in a more modular way, but I'm stumped by the quoting rules of the Bash shell.</p>
  <pre><code>#/bin/sh
  CALCULATE='bc'
  NOW=&quot;perl -e 'use Time::HiRes qw(time); print time'&quot;
  START_TIME=`$NOW`
  [Some long running task ...]
  ELAPSED_TIME=$(echo &quot;($NOW - $START_TIME)&quot; | $CALCULATE)
  echo $ELAPSED_TIME
  </code></pre>
  <p>Bash complains that something is not quoted properly. Why doesn't Bash just expand the command in $NOW and pass it to the backtick to be executed?</p>
  <p>I tried various ways to embed Perl code in a shell script variable, but I can't seem to get it right.</p>
  <p>How can I quote Perl code inside a shell script correctly?</p>