如何执行存储在shell脚本变量中的Perl代码?

Gen*_*neQ 6 bash perl escaping

我有一个脚本调用Perl的Time :: HiRes模块来计算经过的时间.基本上,脚本通过传递以下单行来获取时间:

use Time::HiRes qw(time); print time
Run Code Online (Sandbox Code Playgroud)

通过后退标记到Perl解释器并获取结果.

#/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 "($END_TIME - $START_TIME)" | bc)
echo $ELAPSED_TIME
Run Code Online (Sandbox Code Playgroud)

我试图以更模块化的方式重写它,但我被bash shell的引用规则所困扰.

#/bin/sh
CALCULATE='bc'
NOW="perl -e 'use Time::HiRes qw(time); print time'"
START_TIME=`$NOW`
[Some long running task ...]
ELAPSED_TIME=$(echo "($NOW - $START_TIME)" | $CALCULATE)
echo $ELAPSED_TIME
Run Code Online (Sandbox Code Playgroud)

Bash抱怨没有正确引用某些内容.为什么bash只是在$ NOW中扩展命令并将其传递给后面的tick来执行?

我尝试了各种方法在shell脚本变量中嵌入perl代码,但似乎无法正确使用它.

任何人都知道如何正确引用shell脚本中的perl代码?

Mat*_*Mat 7

使用函数是最直接的方法,我认为:

#! /bin/bash

now() {
    perl -e 'use Time::HiRes qw(time); print time';
}

calc=bc
time1=$(now)
time2=$(now)
elapsed=$(echo $time2 - $time1 | $calc)
echo $elapsed $time1 $time2
Run Code Online (Sandbox Code Playgroud)

基本上不需要引用.